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 ?

Zuckjet
  • 807
  • 1
  • 10
  • 19

1 Answers1

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.

Evert
  • 93,428
  • 18
  • 118
  • 189