Skip to content

narrowing doesn't work #11433

Description

latest nightly build as of October 6, 2016:

interface A { kind: 'A'; a: number; }
interface B { kind: 'B'; b: number; }
type AB = A | B;
export function toResult<Z extends { kind: K; }, K extends string>(
    value: AB | Z,
    orElse: (value: Z) => number
): number {
    switch (value.kind) {
        case 'A': return value.a; // <-- problem, value isn't narrowed to A
        case 'B': return value.b;
        default: return orElse(value);
    }
}

Activity

  1. zpdDG4gta8XKpMCd commented on Oct 7, 2016

    @zpdDG4gta8XKpMCd
    Author
  2. added this to the milestone on Oct 10, 2016
  3. ahejlsberg commented on Oct 13, 2016

    @ahejlsberg
    Member

    I don't think this is a bug. We don't know for sure that Z's kind property isn't 'A' or 'B' (it could basically be any string value), so we can't safely narrow to A or B in the switch cases.

  4. zpdDG4gta8XKpMCd commented on Oct 13, 2016

    @zpdDG4gta8XKpMCd
    Author

    i see your point, negating type constraints (#7993) could have guaranteed that Z.kind is neither A nor B:

    export function toResult<Z extends { kind: K; }, K extends string unlike 'A', 'B'>(
    
  5. removed this from the milestone on Apr 26, 2018
  6. locked and limited conversation to collaborators on Jul 31, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugA bug in TypeScript

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions