TypeScript set string = null fails, but null! works

Viewed 46

In my TypeScript class, why does this fail:

export class MyClass {
    x:string = null //throws IDE warning (type 'null' is not assignable to 'String')
}

but this works:

export class MyClass {
    x:string = null!
}

I don't understand what null! even is. A guaranteed-to-be-not-null null?

1 Answers

! asserts not null, so it removes the null type, leaving you with the empty union, or never. The never type is special in that it is a subtype of every type and is assignable to every type (since it should never happen). That's why you get no error.

For the record, you can verify this yourself:

const x = null!; // mouse over x and you'll see that it's type "never"

const y: string = 42 as never; // this doesn't error since never is assignable to everything
Related