Search code examples
typescriptsettingsasserttranspilernon-nullable

How to make typescript throw runtime error on failed non-null assertion?


Is there a setting to make typescript compile non-null assertions into javascript that throws an error?

By default the non-null assertion is discarded (playground):

// Typescript:
function foo(o: {[k: string]: string}) {
    return "x is " + o.x!
}
console.log(foo({y: "ten"}))

// Compiled into this js without warnings:
function foo(o) {
    return "x is " + o.x;
}
console.log(foo({ y: "ten" }));
// output: "x is undefined"

I want a setting or extension or something that makes it compile into this:

function foo(o) {
    if (o.x == null) { throw new Error("o.x is not null") }
    // console.assert(o.x != null) would also be acceptable
    return "x is " + o.x;
}

Is there any way to convert non-null exclamation point assertions into javascript assertions or errors?


Solution

  • One option is to write your own as a macro, using something like macro-ts. A feature like that will never be in typescript, since the project aims exclusively at build-time (static) type checking, as Alex Wayne explained.