Skip to content
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

Compilation error with possibly nullable object #15482

Closed
jurajkocan opened this issue Apr 30, 2017 · 3 comments
Closed

Compilation error with possibly nullable object #15482

jurajkocan opened this issue Apr 30, 2017 · 3 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@jurajkocan
Copy link

TypeScript Version: 2.3.2

Code

export const Fun1 = (): [string, null] | [null, string] => {
    return [null, 'string'];
};

export const Fun2 = (): string => {
    const [val1, val2] = Fun1();
    if (val1) {
        return val1;
    }
    return val2;
// compiler dosn't know val2 can't be ever null
};

Expected behavior:

No error

Actual behavior:

Type 'string | null' is not assignable to type 'string'.
Type 'null' is not assignable to type 'string'.

Detail

This seems like 10198, i have already new version of typescript but this is still not fixed.

@kitsonk
Copy link
Contributor

kitsonk commented May 1, 2017

It seems like for objects, the compiler properly tracks the types, as this works:

export const Fun3 = (): { val1: string; val2: null } | { val1: null; val2: string } => {
    return { val1: null, val2: 'string' };
};

export const Fun4 = (): string => {
    const { val1, val2 } = Fun3();
    if (val1) {
        return val1;
    }
    return val2;
};

So it seems the compiler doesn't properly track and narrow tuple members in the same way it does object property members.

@mhegazy
Copy link
Contributor

mhegazy commented May 1, 2017

The type of one of the keys is not a discriminant. in both examples, the type of val2 is string|null narrowing val1 does not narrow the type of the return value of func3.

Moreover, it is really hard to for the compiler to build a relationship between two variables in such a destructuring pattern.

see: #14630, #10976, #12263, #10065, and #10846

@mhegazy mhegazy added the Design Limitation Constraints of the existing architecture prevent this from being fixed label May 1, 2017
@mhegazy
Copy link
Contributor

mhegazy commented May 19, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

3 participants