Skip to content

Type inference of discrimitated union uses "widest" option #60920

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
6 tasks done
matthieusieben opened this issue Jan 6, 2025 · 2 comments
Closed
6 tasks done

Type inference of discrimitated union uses "widest" option #60920

matthieusieben opened this issue Jan 6, 2025 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@matthieusieben
Copy link

πŸ” Search Terms

inference discriminated union narrowing ternary

βœ… Viability Checklist

⭐ Suggestion

type Unknown = {$type: string}

type B = {$type: 'b'; str: string}
const b: B = {$type: 'b', str: 'foo'}

type A = {$type: 'a'; num: number; embed: B | Unknown}
function isA<V extends {$type?: string}>(v: V): v is V & A {
  return v.$type === 'a'
}

const a: A = {$type: 'a', num: 42, embed: b}

const maybeA: A | B = a

// typed as `Unknown` instead of `Unknown | B`
const result = isA(maybeA) ? maybeA.embed : b

// return type is not `Unknown | B`
function getEmbed(v: A | B) {
  if (isA(v)) return v.embed
  return v
}

Playground

πŸ“ƒ Motivating Example

Better preserve inferred types when working with discriminated unions.

πŸ’» Use Cases

  1. What do you want to use this for? A distributed network that allows for custom entity types (atproto)
  2. What shortcomings exist with current approaches? Working with data of partially known types is hard(er)
  3. What workarounds are you using in the meantime? Explicit typings
@Andarist
Copy link
Contributor

Andarist commented Jan 6, 2025

To quote @MartinJohns:

This is working as intended and happens because of type reduction. See #50171 and many many others.

Also: https://www.typescriptlang.org/docs/handbook/type-inference.html#best-common-type

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jan 6, 2025
@matthieusieben
Copy link
Author

I wasn't aware of the "Best common type" type inference strategy. Thanks for pointing it out. Sorry about the noise πŸ™.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

3 participants