Skip to content

Compilation error with possibly nullable object #15482

Closed

Description

@jurajkocan

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.

Activity

  1. kitsonk commented on May 1, 2017

    @kitsonk
    Contributor

    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.

  2. mhegazy commented on May 1, 2017

    @mhegazy
    Contributor

    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

  3. mhegazy commented on May 19, 2017

    @mhegazy
    Contributor

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

  4. locked and limited conversation to collaborators on Jun 14, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions