microsoft/TypeScript

Unsound type inference with `in` operator on union

kaya3 opened this issue · 2 comments

kaya3 commented

TypeScript Version: 3.8.0-dev.20191105

Search Terms: in operator, union, unsound

Code

type Union = { foo: string; foo2: string } | { bar: number; bar2: number };

const union: Union = { foo: 'a', bar: 1, bar2: 2 };

if('foo' in union) {
    union; // incorrectly inferred as { foo: string, foo2: string }
}

Expected behavior: Type of union should be narrowed to Union & { foo: any }, or not narrowed.

Actual behavior: Type of union is narrowed to { foo: string, foo2: string } despite having no foo2 property.

Playground Link: http://www.typescriptlang.org/play/?ts=3.8.0-dev.20191105&ssl=1&ssc=1&pln=8&pc=1#code/C4TwDgpgBAqgdgSwPZygXigbygMyUgLigGdgAnBOAcwG5d8AmI0i6qAXygB8soAjAIZkicAK4BbPhDJ1BZJlDGTpHGgCg1AYxSkooxCiLxkqDNjyEoAcgFWANPyFEAjA7kKGqjQhwAKKxZWUJR6BnAAlFhqUDGhJnQA9AnBcNpkZBCawAA2ICk40hkAJlACxLwWzOSUVA4WCiw1HGrsakA

This was discussed when the feature was implemented: link

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.