microsoft / microsoft/TypeScript

suggest `in` operator when accessing non-common property of union types

Open
#45,211 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Experience Enhancement Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

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
}

💻 Use Cases

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the TypeScript compiler's implementation and tests for diagnostic 2339 and related suggestion diagnostics. Confirm the behavior for property access inside an if condition, then add the proposed in-operator suggestion with tests covering union types and verify the diagnostic wording.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.