Skip to content

suggest in operator when accessing non-common property of union typesΒ #45211

Open
@Zzzen

Description

@Zzzen

πŸ” 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
}

πŸ’» Use Cases

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions