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: IsUnion #236

Open
zikaari opened this issue Jul 29, 2021 · 3 comments
Open

Proposal: IsUnion #236

zikaari opened this issue Jul 29, 2021 · 3 comments

Comments

@zikaari
Copy link

zikaari commented Jul 29, 2021

Inspired by - https://stackoverflow.com/a/53955431/5039290

type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;

Use case

Create a specific type that guarantees only unions from a generic type that could be mixed-bag.

type MemberInfo = {
  first_name: string;
  last_name: string;
  date_of_birth: number;
  favourite_fruit: 'apple' | 'mango' | 'banana';
  industry: 'tech' | 'art' | 'medicine';
}

type ChoiceBasedField = {
  [K in keyof MemberInfo]: IsUnion<MemberInfo[K]> extends true ? K : never
}[keyof RespondentFields];

// can accept 'favourite_fruit' or 'industry', but errors on anything else
const renderDropdown = (field: ChoiceBasedField) => (
  <select> ... </select>
);

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
@sindresorhus
Copy link
Owner

Sounds like a useful type.

@sindresorhus sindresorhus added enhancement New feature or request type addition labels Jul 29, 2021
@fregante fregante removed the enhancement New feature or request label Aug 13, 2024
@Mouvedia
Copy link

@sindresorhus can you expose

export type IsUnion<T> = InternalIsUnion<T>;

?

@sindresorhus
Copy link
Owner

#676

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

Successfully merging a pull request may close this issue.

4 participants