microsoft/BosqueLanguage

Type checking in JS

Closed this issue · 2 comments

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.

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;
}

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.