2

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?

Luke Miles
  • 941
  • 9
  • 19
  • I'd say – don't use non-null assertion. Most likely you can restructure your code in such a way that you won't need them. – rsmeral May 28 '21 at 21:13

2 Answers2

3

Nope.

The non-null assertion is specifically telling the compiler that you know better than it does. It's purely a construct for managing type information. But if you don't know better then the compiler, then you'll have to handle it yourself.

This is a feature best left avoided entirely for the sake of type safety (except for rare occassions where you can be 100% certain the value is non null), and there's even some help from eslint to let you know it's dangerous in the no-non-null-assertion rule


The good news, I guess, is that if you asserted the value is non null, but it is null, then your program will probably end up crashing anyway, somewhere...

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
1

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.

Luke Miles
  • 941
  • 9
  • 19