Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active April 1, 2022 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfet97/5b25f7642be1ac9cd4fe1441abc45e87 to your computer and use it in GitHub Desktop.
Save jfet97/5b25f7642be1ac9cd4fe1441abc45e87 to your computer and use it in GitHub Desktop.
Use intersections to filter unions
type Decision = "yes" | "no" | 1 | 0 | true | false;
type JustStrings = Decision & string;
/// = ("yes" | "no" | 1 | 0 | true | false) & string
/// = | ("yes" & string) | ("no" & string)
/// | (1 & string) | (0 & string)
/// | (true & string)| (false & string))
/// = "yes" | "no" | never | never | never | never
/// = "yes" | "no"
//
// when mapping types, if I want to extract the string keys I generally prefer & string to Extract
type GetMethods<T extends object> = {
[P in keyof T & string as `get${Capitalize<P>}`]: () => T[P];
};
type R = GetMethods<{ foo: string; 0: number }>;
// = { getFoo: () => string; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment