Skip to content

Use NonNullable<T> in more scenarios - #49330

Merged
Anders Hejlsberg (ahejlsberg) merged 4 commits into
mainfrom
nullableImprovements
Jun 1, 2022
Merged

Use NonNullable<T> in more scenarios#49330
Anders Hejlsberg (ahejlsberg) merged 4 commits into
mainfrom
nullableImprovements

Conversation

@ahejlsberg

Copy link
Copy Markdown
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):

functionf1<T>(x: T){lety=x||"hello";// Now NonNullable<T> | string, previously T | string}functionerror(): never{thrownewError();}functionf2<T>(x: T){// Now NonNullable<T>, previously Treturnx||error();}functionf3(x: unknown){lety=x!;// {}}functionf4<Textends{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(typeofobj?.x==="string"){obj;// Now NonNullable<T>, previously T}}

@ahejlsberg
Anders Hejlsberg (ahejlsberg) deleted the nullableImprovements branch June 1, 2022 00:05
@DanielRosenwasser

Copy link
Copy Markdown
Member

FWIW this added about 100ms to Compiler-Unions

image

Sign up for freeto subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Author: TeamFor Uncommitted BugPR for untriaged, rejected, closed or missing bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants

@ahejlsberg@DanielRosenwasser@weswigham@RyanCavanaugh@typescript-bot