GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Control flow based type analysis by ahejlsberg · Pull Request #8010 · microsoft/TypeScript

Conversation

@ahejlsberg

@ahejlsberg Anders Hejlsberg (ahejlsberg) commented Apr 11, 2016

Copy link
Copy Markdown
Member

This PR introduces control flow based type analysis for local variables and parameters as initially suggested in #2388 and prototyped in #6959. Previously, the type analysis performed for type guards was limited to if statements and ?: conditional expressions and didn't include effects of assignments and control flow constructs such as return and break statements. With this PR, the type checker analyses all possible flows of control in statements and expressions to produce the most specific type possible (the narrowed type) at any given location for a local variable or parameter that is declared to have a union type.

Some examples:

function foo(x: string | number | boolean) {
    if (typeof x === "string") {
        x; // type of x is string here
        x = 1;
        x; // type of x is number here
    }
    x; // type of x is number | boolean here
}

function bar(x: string | number) {
    if (typeof x === "number") {
        return;
    }
    x; // type of x is string here
}

Control flow based type analysis is particuarly relevant in --strictNullChecks mode because nullable types are represented using union types:

function test(x: string | null) {
    if (x === null) {
        return;
    }
    x; // type of x is string in remainder of function
}

Furthermore, in --strictNullChecks mode, control flow based type analysis includes definite assignment analysis for local variables of types that don't permit the value undefined.

function mumble(check: boolean) {
    let x: number; // Type doesn't permit undefined
    x; // Error, x is undefined
    if (check) {
        x = 1;
        x; // Ok
    }
    x; // Error, x is possibly undefined
    x = 2;
    x; // Ok
}

The narrowed type of a local variable or parameter at a given source code location is computed by starting with the initial type of the variable and then following each possible code path that leads to the given location, narrowing the type of the variable as appropriate based on type guards and assignments.

  • The initial type of local variable is undefined.
  • The initial type of a parameter is the declared type of the parameter.
  • The initial type of an outer local variable or a global variable is the declared type of that variable.
  • A type guard narrows the type of a variable in the code path that follows the type guard.
  • An assignment (including an initializer in a declaration) of a value of type S to a variable of type T changes the type of that variable to T narrowed by S in the code path that follows the assignment.
  • When multiple code paths lead to a particular location, the narrowed type of a given variable at that location is the union type of the narrowed types of the variable in those code paths.

The type T narrowed by S is computed as follows:

  • If T is not a union type, the result is T.
  • If T is a union type, the result is the union of each constituent type in T to which S is assignable.

Thanks to Ivo Gabe de Wolff (@ivogabe) for providing inspiration and tests for this PR.

Fixes #2388.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

HerringtonDarkholme, cevek, danielepolencic, svieira, jednano, RobertoUa, SlurpTheo, alitaheri, AbubakerB, NoelAbrahams, and 11 more reacted with thumbs up emoji RyanCavanaugh, mquandalle, jwbay, tinganho, svieira, jednano, ViIvanov, drub0y, RobertoUa, NoahZhang, and 13 more reacted with hooray emoji weswigham, mquandalle, mhegazy, svieira, jednano, elisee, toolness, RobertoUa, pkondzior, alitaheri, and 21 more reacted with heart emoji
All reactions
  • 👍 21 reactions
  • 🎉 23 reactions
  • ❤️ 31 reactions
Anders Hejlsberg (ahejlsberg) and others added 30 commits March 22, 2016 10:20
@ahejlsberg
Initial implementation of control flow based type analysis
e67d15a
@ahejlsberg
Add type annotations to suppress circularity errors
afa1714
@ahejlsberg
Fixing tests
7c45c7b
@ahejlsberg
Accepting new baselines
80c2e5e
@ahejlsberg
Adding a few optimizations
33985b2
@ahejlsberg
Handle assignment of union types in getAssignmentReducedType
ed5002c
@ahejlsberg
Remove incorrect type predicate (could be true even when result is fa…
6d25a42
…lse)
@ahejlsberg
Fix overly aggressive optimization
bf78470
@ivogabe
Add control flow tests
4f936c4
@ahejlsberg
Merge pull request #7690 from ivogabe/controlFlowTypesTest
7f02357
Adds tests to control flow types branch
@ahejlsberg
Fix issues in analysis of do..while and for..in/for..of
9e965d4
@ahejlsberg
Fix comment in test
9de0a5d
@ahejlsberg
Accepting new baselines
560bc3f
@ahejlsberg
Fixing some tests
0820249
@ahejlsberg
Accepting new baselines
5a5d89a
@ahejlsberg
Use type {} for vacuous type guards / New getTypeWithFacts function
424074b
@ahejlsberg
Remove unnecessary cast
c6f4de3
@ahejlsberg
Fix some tests
e53f390
@ahejlsberg
Accepting new baselines
a38d863
@ahejlsberg
Delete removeNullableKind, use getTypeWithFacts instead
3d0fa31
@ahejlsberg
Support unknown types (host object names) in typeof type guards
ce81ba5
@ahejlsberg
Separate error messages for 'null', 'undefined', or both.
354fd10
@ahejlsberg
Flow analysis of &&, ||, and destructuring assignments
5179dd6
@ahejlsberg
Accepting new baselines
019f5bd
@ahejlsberg
Handle shorthand property assignments
f13c92f
@ahejlsberg
Accepting new baselines
b03d087
@ahejlsberg
Support destructuring declarations in control flow analysis
7a32129
@ahejlsberg
Accepting new baselines
6fb9424
@ahejlsberg
Adding test
e45bac8
@ahejlsberg
Fixing fourslash tests
7dfcad6
Anders Hejlsberg (ahejlsberg) added 2 commits April 21, 2016 13:02
@ahejlsberg
Support assignments in truthiness type guards
8a0bc3b
@ahejlsberg
Adding test
d2b89be
This was referenced Apr 21, 2016
Narrowing does not work for variables typed with type parameters #6445
Closed
Narrow type constraints #7422
Closed
Anders Hejlsberg (ahejlsberg) added 6 commits April 21, 2016 13:40
@ahejlsberg
Removing unused logic
ab4b039
@ahejlsberg
Correct issue with exported variables in code flow analysis
e12b2a7
@ahejlsberg
Update fourslash test
4fb31ac
@ahejlsberg
Only narrow to {} in getNarrowedType when types are completely unrelated
f06d3f6
@ahejlsberg
Revert previous change
42e3fc4
@ahejlsberg
Accepting new baselines
0dee5ad
@ahejlsberg
Anders Hejlsberg (ahejlsberg) merged commit 5ed6f30 into master Apr 22, 2016
Basarat Ali Syed (basarat) added a commit to alm-tools/alm that referenced this pull request Apr 22, 2016
@basarat
update ts to latest for microsoft/TypeScript#8010 🌹
c9448ed
@mhegazy Mohamed Hegazy (mhegazy) mentioned this pull request Apr 22, 2016
Control flow based type guards #6959
Closed
5 tasks done
@mquandalle Maxime Quandalle (mquandalle) mentioned this pull request Apr 23, 2016
WIP: Member-type based type guards #6062
Closed
4 tasks
@yortus Troy Gerwien (yortus) mentioned this pull request Apr 26, 2016
Errors issued for working code due to narrowing behaviour #7160
Closed
This was referenced Apr 26, 2016
Suggestion: non-nullable type #185
Closed
Expanded type guard suggestions #4868
Closed
@SlurpTheo SlurpTheo mentioned this pull request Apr 26, 2016
TypeChecker::getTypeAtLocation(Identifier) does not Return Narrowed Type Inside an Array.isArray()-Based Type Guard #8094
Closed
@mhegazy Mohamed Hegazy (mhegazy) mentioned this pull request Apr 29, 2016
Early return instead of "else" causes compiler error. #8365
Closed
dokidokivisual commit bot (dokidokivisual) added a commit to karen-irc/karen that referenced this pull request May 4, 2016
@dokidokivisual
Auto merge of #604 - saneyuki:nullable, r=saneyuki
25ed88b
chore(TypeScript): Enable 'strictNullChecks' option

This tries to enable [`--strictNullChecks` option](microsoft/TypeScript#7140) of TypeScript compiler.

- [Non-nullable types by ahejlsberg · Pull Request #7140 · Microsoft/TypeScript](microsoft/TypeScript#7140)
  - [Non-strict type checking · Issue #7489 · Microsoft/TypeScript](microsoft/TypeScript#7489)
  - [[Request for feedback] Nullable types, `null` and `undefined` · Issue #7426 · Microsoft/TypeScript](microsoft/TypeScript#7426)
- [Control flow based type analysis by ahejlsberg · Pull Request #8010 · Microsoft/TypeScript](microsoft/TypeScript#8010)

<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.io/review_button.svg" height="35" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/karen-irc/karen/604)
<!-- Reviewable:end -->
@kristian-puccio

Kristian Puccio (kristian-puccio) commented May 16, 2016

Copy link
Copy Markdown

Just trying out typescript now and working out for to get type check actions in redux. Looks like this feature could be very helpful for this?

reduxjs/redux#992

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@mhegazy
Mohamed Hegazy (mhegazy) deleted the controlFlowTypes branch May 16, 2016 17:33
@yortus Troy Gerwien (yortus) mentioned this pull request May 18, 2016
Control flow based type narrowing for assert(...) calls #8655
Closed
@ahejlsberg Anders Hejlsberg (ahejlsberg) mentioned this pull request May 31, 2016
Type inference - code after early return from an 'if' should infer the same type as the 'else' block would #8886
Closed
@yortus Troy Gerwien (yortus) mentioned this pull request Jun 9, 2016
Primitive type guards require typeof to be on the left hand side of the comparison #9020
Closed
@realityfilter realityfilter mentioned this pull request Jul 8, 2016
control flow based type analysis for type guards broken in 2.0 dev build #9569
Closed
@ivogabe Ivo Gabe de Wolff (ivogabe) mentioned this pull request Jul 13, 2016
Type narrowing is not allowed if variable is reassigned after the use site inside if block #1764
Closed
@yortus Troy Gerwien (yortus) mentioned this pull request Jul 21, 2016
Type guard failures that become an intersection type #9859
Closed
@dmitry-a-morozov Dmitry Morozov (dmitry-a-morozov) mentioned this pull request Mar 22, 2017
Flow based null check analysis for [<AllowNullLiteralAttribute>] types and alike fsharp/fslang-suggestions#552
Closed
3 of 6 tasks
@microsoft Microsoft (microsoft) locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Reviewers

1 more reviewer
@birbilis George Birbilis (birbilis) birbilis left review comments
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

14 participants

@ahejlsberg @jods4 @RyanCavanaugh @ivogabe @zpdDG4gta8XKpMCd @JsonFreeman @thebanjomatic @kristian-puccio @sandersn @DanielRosenwasser @weswigham @birbilis @mhegazy @msftclas
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.