Skip to content

Infer types in unionsΒ #51349

Closed
Closed
@jnordberg

Description

@jnordberg

Suggestion

This should work:

interface A {
    foo: string
}

interface B {
    bar: string
}

type C = A | B

const a = {foo: 'bar'} as C

if (a.foo) {
    console.log(a.foo)
} else {
    console.log(a.bar)
}

I think the compiler should be able to infer the types here. Its a very common pattern to return e.g. (SuccessResponse | ErrorResponse) and without inference it becomes very inconvenient to handle. I apologize if this has been discussed before, it seems like it should have been but I couldn't find anything with a quick search.

Playground

πŸ” Search Terms

Infer 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions