148

I have an object X with a method getY() returning an object Y with a method a(), in typescript. What does it mean an expression like this one:

X.getY()!.a()

I guess the ! operator is used to check against null, but how does it work concretely? Where is defined in the language?

3 Answers 3

170

It's called the "Non-null assertion operator" and it tells the compiler that x.getY() is not null.

It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
    // Throw exception if e is null or invalid entity
}

function processEntity(e?: Entity) {
    validateEntity(e);
    let s = e!.name;  // Assert that e is non-null and access name
}

Edit

There's an issue for documenting this feature: Document non-null assertion operator (!)

Sign up to request clarification or add additional context in comments.

10 Comments

wow. ive probably written e && e.name a couple thousand times. thanks
@Tope do not confuse this with a 'null safety operator' of other languages (a?.b?.c?.d?). This simply tells typescript compiler that a variable is not null, which may be false and it will crash at runtime
What would be a good use case for it? Because if I have to check for null anyway doesn't that beats the purpose?
@StLia What if you know for sure that something isn't null and you don't want/need to check for null?
@Rishav yes, you're right about the (javascript) optional chaining operator, and you're also correct about the (typescript) non-null assertion operator. but they also mean completely different things. The first says "i'm not sure, it can be null, but if not go ahead and..." but the later says "i'm 100% sure that it is not null".
|
45

Non-null assertion operator: !

  • You tells the TS compiler that the value of a variable is not null | undefined
  • Use it when you are in possession of knowledge that the TS compiler lacks.

Here is a trivial example of what it does:

let nullable1: null | number;
let nullable2: undefined | string;

let foo  = nullable1! // type foo: number
let fooz = nullable2! // type fooz: string

It basically removes null | undefined from the type


When do I use this?

Typescript is already pretty good at inferring types for example using typeguards:

let nullable: null | number | undefined;

if (nullable) {
    const foo = nullable; // ts can infer that foo: number, since if statements checks this
}

However sometimes we are in a scenario which looks like the following:

type Nullable = null | number | undefined;

let nullable: Nullable;

validate(nullable);

// Here we say to ts compiler:
// I, the programmer have checked this and foo is not null or undefined
const foo = nullable!;  // foo: number

function validate(arg: Nullable) {
    // normally usually more complex validation logic
    // but now for an example
    if (!arg) {
        throw Error('validation failed')
    }
}

My personal advice is to try to avoid this operator whenever possible. Let the compiler do the job of statically checking your code. However there are scenarios especially with vendor code where using this operator is unavoidable.

Comments

0

It gets rid of the typescript compile error, when a variable can be of type null/undefined and you are performing a function on that variable which requires it be non-null/non-undefined.

function getValue(): string | undefined {
    return "MyStr"; // TS assumes getValue can return undefined as well
  //return undefined;
  //return OutsidePlugin(); // The plugin can return both string and undefined, e.g.
}
            
let value = getValue();
console.log('value length: ' + value.length); //value.length can requires non-undefined

This will generate the following Typescript compile error:

'value' is possibly 'undefined'.

Non-null assertion operator is just a quick escape hatch:

console.log('value length: ' + value!.length); //TS, I assure you it's non-undefined

2 Comments

it generates value length: 5, and no error, at w3schools.com/typescript/…
Because you are using value! in your example already and then w3school not showing errors without ! TS by default compiles to js even with errors. Check the official compiler here: typescriptlang.org/play/?#code/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.