sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
14k stars 531 forks source link

Proposal: `IsUnion` #236

Open zikaari opened 3 years ago

zikaari commented 3 years ago

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

Fund with Polar

sindresorhus commented 3 years ago

Sounds like a useful type.