2

Control flow analysis for destructured discriminated unions by ahejlsberg · Pull...

 2 years ago
source link: https://github.com/microsoft/TypeScript/pull/46266
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Copy link

Member

ahejlsberg commented 27 days ago

edited

This PR implements control flow analysis for dependent parameters and variables declared by destructuring discriminated unions. Specifically, when non-rest binding elements are declared as const variables or const-like parameters (parameters for which there are no assignments in the function body) and the parent type for the destructuring is a discriminated union type, conditional checks for variables destructured from discriminant properties now affect the types of other variables declared in the same destructuring.

Some examples:

type Action =
    | { kind: 'A', payload: number }
    | { kind: 'B', payload: string };

function f10({ kind, payload }: Action) {
    if (kind === 'A') {
        payload.toFixed();
    }
    if (kind === 'B') {
        payload.toUpperCase();
    }
}

function f11(action: Action) {
    const { kind, payload } = action;
    if (kind === 'A') {
        payload.toFixed();
    }
    if (kind === 'B') {
        payload.toUpperCase();
    }
}

function f12({ kind, payload }: Action) {
    switch (kind) {
        case 'A':
            payload.toFixed();
            break;
        case 'B':
            payload.toUpperCase();
            break;
        default:
            payload;  // never
    }
}

function f13(it: Iterator<number>) {
    const { value, done } = it.next();
    if (!done) {
        value;  // number
    }
}

Fixes #10830.
Fixes #35283.
Fixes #38020.
Fixes #46143.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK