Skip to content
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

Proposal: NonDiscriminatedUnion #386

Closed
RebeccaStevens opened this issue Mar 30, 2022 · 2 comments
Closed

Proposal: NonDiscriminatedUnion #386

RebeccaStevens opened this issue Mar 30, 2022 · 2 comments

Comments

@RebeccaStevens
Copy link
Contributor

RebeccaStevens commented Mar 30, 2022

For a union of only 2 elements, this would just be:

type NonDiscriminatedUnion<Union> = Union | UnionToIntersection<Union>

However, the type would be more complex for the case of 3 or more elements.

Example usage

Given these types:

type Foo =
  | {
      bar: number;
    }
  | {
      baz: string;
      qux?: number;
    };

type NonDiscriminatedFoo = NonDiscriminatedUnion<Foo>;

If you have a value typed as NonDiscriminatedFoo

declare const value: NonDiscriminatedFoo;

You can access each part of the union independently.

// No benefit over normal union.
if ('bar' in value) {
    // `value ` will be typed as `{ bar: number; }`
}

// No benefit over normal union.
if ('baz' in value) {
    // `value` will be typed as `{ baz: string; qux?: number; }`
}

// This benefits from the non-discriminated union
if ('bar' in value && 'baz' in value) {
    // `value` will be typed as `{ bar: number; baz: string; qux?: number; }`
    // `value` would be `never` with a normal union
}

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@TkaczykAdam
Copy link

TkaczykAdam commented May 3, 2022

I'm looking for this type too. I found a solution here and it's working fine but it's a lot of code. It will be great to have NonDiscriminatedUnion<T> or AllFields<T>

@JGJP
Copy link

JGJP commented Jan 16, 2024

Isn't this covered by UnionToIntersection?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants