Skip to content

Instantly share code, notes, and snippets.

@bazzooka
Last active January 27, 2022 23:20
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 bazzooka/064774a4ab76db9a24c06754f654a580 to your computer and use it in GitHub Desktop.
Save bazzooka/064774a4ab76db9a24c06754f654a580 to your computer and use it in GitHub Desktop.
Snippets Typescript
const roles = ['read', 'write', 'readAndWrite'] as const;
type Roles = typeof roles[number];
// equals to this
// type Roles = "read" | "write" | "readAndWrite"
// or even like this
type RolesInCapital = Capitalize<typeof roles[number]>;
// equals to this
// type RolesInCapital = "Read" | "Write" | "ReadAndWrite"
// The `infer` keyword
const User = {
id: 123,
username: 'John',
email: 'john@gmail.com',
addons: [
{ name: 'WriteAddon', id: 1 },
{ name: 'TodoAddon', id: 2 }
]
};
type UnpackArray<T> = T extends (infer R)[] ? R: T;
type AddonType = UnpackArray<typeof User.addons>; // { name: string, id: number }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment