2

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
  • Yeah, I'd expect that to produce the type never (which would not be assignable). Same thing here: const y = 5 as never; const x: string = y; doesn't error Commented Jan 4, 2021 at 19:17

1 Answer 1

3

! 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.