Skip to content

Conversation

ahejlsberg
Copy link
Member

This PR builds on #49119 to use NonNullable<T> in more scenarios in --strictNullChecks mode. The PR also cleans up some compiler internals.

  • Instantiations of NonNullable<T> are now only created only if T can possibly be null or undefined. Previously, the compiler would sometimes create NonNullable<T> instantiations even for a T constrained to a non-nullable type.
  • Given expressions a and b of type A and B, the expression a || b now has type NonNullable<A> | B if A can possibly be null or undefined.
  • Given an expression obj of a generic type T constrained to a nullable type, when an expression obj?.x is used in a context that proves x is not undefined, the type of obj is narrowed to NonNullable<T>.
  • Given an expression x of type unknown, the expression x! has type {}.
  • The getFalsyFlags function is gone and its functionality folded into getTypeFacts.

Some examples (in --strictNullChecks mode):

function f1<T>(x: T) {
    let y = x || "hello";  // Now NonNullable<T> | string, previously T | string
}

function error(): never {
    throw new Error();
}

function f2<T>(x: T) {  // Now NonNullable<T>, previously T
    return x || error();
}

function f3(x: unknown) {
    let y = x!;  // {}
}

function f4<T extends { x: string | number } | undefined>(obj: T) {
    if (obj?.x === "hello") {
        obj;  // Now NonNullable<T>, previously T
    }
    if (obj?.x) {
        obj;  // Now NonNullable<T>, previously T
    }
    if (typeof obj?.x === "string") {
        obj;  // Now NonNullable<T>, previously T
    }
}

@ahejlsberg ahejlsberg merged commit 3cdb808 into main Jun 1, 2022
@ahejlsberg ahejlsberg deleted the nullableImprovements branch June 1, 2022 00:05
@DanielRosenwasser
Copy link
Member

FWIW this added about 100ms to Compiler-Unions

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants