Open
Description
π Search Terms
access to non-common property of union types, suggest in operator for union types
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
Background: https://twitter.com/kentcdodds/status/1420125238436655104?s=21
When accessing props that are not on all union types, tsc gives Property 'foo' does not exist on type 'XX'
, which is confusing to newcomers. We can suggest the in
operator when it is used inside if
condition.
π Motivating Example
type A = {one: string}
type B = {two: string}
type C = A | B
declare const thing: C
// πBefore:
// Property 'two' does not exist on type 'C'.
// Property 'two' does not exist on type 'A'.(2339)
if (thing.two) {
// it's a B
}
// πAfter:
// Property 'two' does not exist on type 'C'.
// Property 'two' does not exist on type 'A'.(2339)
// Did you mean to use `'two' in thing`?
if (thing.two) {
// it's a B
}