Skip to content

Use NonNullable<T> in more scenarios #49330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 1, 2022
Merged

Use NonNullable<T> in more scenarios #49330

merged 4 commits into from
Jun 1, 2022

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