Skip to content
This repository has been archived by the owner on Nov 16, 2023. It is now read-only.

Type checking in JS #55

Closed
chriskuech opened this issue Apr 19, 2019 · 2 comments
Closed

Type checking in JS #55

chriskuech opened this issue Apr 19, 2019 · 2 comments
Labels
design discussion Language design discussion issue enhancement New feature or request

Comments

@chriskuech
Copy link

JavaScript is almost always used to deal with dynamic input sources, like payloads from APIs. One of the biggest drawbacks to TypeScript is its purely static type system with no way to automatically convert any to the expected stronger type (TypeScript default settings will even not alert you to the unsafe cast), without manually implementing type guards.

I can't find any information on whether Bosque is dynamically or statically typed, but it would be awesome if Bosque could detect type casts and emit a type validation function for that operation. It would gain a huge advantage over TypeScript.

@mrkmarron
Copy link
Contributor

Bosque is statically typed, with records, tuples, objects, union, and (limited) intersection types.

In Bosque the open record type {...} is a record with some number of properties with unknown names. We allow type checks and casts with the syntax:

function foo(arg: {...}): {f:Int, g:Int} | {f:String, g:Bool} | None {
    //check if arg is of type {f:Int, g:Int}
    if(arg->is[{f:Int, g:Int}](arg)) {
        return arg->as[{f:Int, g:Int}](); //cast to type
    }

    return arg->tryAs[{f:String, g:Bool}](); //try cast or return None if it fails
}

Currently we don't have a nice JSON interop story and I would like to do something here. From your comment I assume you are thinking something like:

function foo(data: String): {f: Int, g: Int} {
var check = JSON::is[{f: Int, g: Int}](data); //check if string is JSON format that is convertable to record type
if(check) {
    return JSON::parse[{f: Int, g: Int}](data); //parse the json string as the given record type
}
else {
    return none;
}

@mrkmarron mrkmarron added design discussion Language design discussion issue enhancement New feature or request labels Apr 20, 2019
@chriskuech
Copy link
Author

I suppose, though that looks pretty verbose. I'd rather just JSON::parse[{f: Int, g: Int}](data) throw an error/return an optional. If Bosque ever had an interop story with TypeScript or JS modules, the general case of converting an any or unknown type to a stronger type would be much more beneficial--I can't remember the last time I called JSON.parse directly.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
design discussion Language design discussion issue enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants