What does `undefined!` means in typescript?
Asked Answered
P

1

8

typescript source code use undefined! in many places. For example, in binder.ts, from line 261 to 271:

            file = undefined!;
            options = undefined!;
            languageVersion = undefined!;
            parent = undefined!;
            container = undefined!;
            thisParentContainer = undefined!;
            blockScopeContainer = undefined!;
            lastContainer = undefined!;
            delayedTypeAliases = undefined!;
            seenThisKeyword = false;
            currentFlow = undefined!;

From typescript official docs, the postfix ! means "Non-null assertion operator", and it's definition is that:

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

So this usage undefined! seems make no sense, because it asserts that undefined is non-undefined.

What is the meaning of undefined!, and why we use in that way ?

Pharmacy answered 17/1, 2021 at 4:11 Comment(3)
Probably "this will never be null in runtime"...Titanic
@Titanic it sounds reasonable, but I have never known this usage, hope more details or docsPharmacy
Possibly relevant answer here - #38875428Tittivate
D
6

So this usage undefined! seems make no sense, because it asserts that undefined is non-undefined.

What is the meaning of undefined!, and why we use in that way ?

Another way to put it is, telling typescript "Shut up, I know what I'm doing". If strictNullChecks is on, Typescript will complain when assigning undefined/null to a value with a type that doesn't include undefined/null.

strictNullChecks is a good default, but there are cases where you might want to assign undefined or null anyway (maybe in a local scope or private part of a library), and you yourself guarantee that you're always going ensure a value is set later.

The benefit is that the user of the library doesn't have to deal with optional properties, and you, as the library author, might have a bit more flexibility about how objects are built before they leave the boundary of your library.

Example:

type MyArticle = {
  title: string;
}

function getArticle(): MyArticle {

  const result:MyArticle = {
    // ignore the undefined error, we're dealing with this later.
    title: undefined!,
  };

  result.title = 'Hello world';
  return result;

}

The above example is contrived. There's better ways to structure it, and I suspect that that's true for the sample you shared as well.

Dyl answered 19/1, 2021 at 6:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.