0

I would like to add custom typing to javascript using a tool like Babel (or similar) to add run-time typing and many other basic error checks into the language but I'm having basic issues simply getting a basic example to work.

I have tried using a regex parsing solution but it causes lots of issues in that it doesn't understand what parts of the code are commented out etc.

I've tried using various AST generators, but I have had no success in modifying them to fit the particular syntax below.

I'd preferably like to use babel to convert/transpile this:

function testFunction(a:integer:>10, b:string:not-empty) {
        
    var test:boolean = true

    return string:`string is ${b} and integer is ${a} and boolean is ${test}`
}

into this

function testFunction(a,b) {
    if (!Number.isInteger(a)) {
        throw new Error('param a on testFunction must be an integer')
    }

    if (a > 10 === false) {
        throw new Error('integer a must be greater than 10')
    }

    if (typeof b !== 'string') {
        throw new Error('param b on testFunction must be a string')
    }

    if (b === '') {
        throw new Error('string b cant be empty')
    }

    var test = true
    if (typeof test !== 'boolean') {
        throw new Error('variable test must be of type boolean')
    }

    var returnValue = `string is ${b} and integer is ${a} and boolean is ${test}`
    if (typeof returnValue !== 'string') {
        throw new Error('return value must be of type string')    
    }
    return returnValue
}

I'd like to build a custom type checking library so I don't want to build this on top of an existing typing library (like typescript)

Tony J Watson
  • 629
  • 2
  • 9
  • 20

1 Answers1

0

Babel doesn't support the addition of custom syntax extensions, so something like

function fn(a:integer:>10, b:string:not-empty){}

would not be workable. You could always explore using additional comments to annotate that things like bounds and size expectations.

That said, it sounds like flow-runtime would be a good fit and implements solutions to the things you've spelled out. It supports the addition of runtime constraints via the flow-runtime-validators package.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251