Skip to content

Instantly share code, notes, and snippets.

@schuhwerk
Created May 14, 2024 10:58
Show Gist options
  • Save schuhwerk/2d90cafa1317dbb49f293db18da37110 to your computer and use it in GitHub Desktop.
Save schuhwerk/2d90cafa1317dbb49f293db18da37110 to your computer and use it in GitHub Desktop.
Typescript Hints
// use the strings in an array as types.
const animals = ["cat", "dog", "mouse"] as const
type Animal = (typeof animals)[number] // transformer like "cat" | "dog" | ...
let myAnimal : Animal = "cat" // <- autocomplete works here
// merge two types.
type Prefix = "sub_"
type Numbers = 0 | 1 | 2 | 3 | 4 | 5
type SubNumbers = `${Prefix}${Numbers}` // transforms to sub_1 | sub_2 | ...
let myNumber : SubNumbers = "sub_0" // <- autocomplete works here
// objects instead of enums.
const Roles = {
Admin: "admin",
Writer: "writer",
Reader: "reader"
} as const
// Convert object key in a type
type RoleKeys = (typeof Roles)[keyof typeof Roles]
declare function hasAccess(role: RoleKeys): void
hasAccess("admin") // works, but no auto-refactoring of keys. would not work with an enum.
hasAccess(Roles.Admin) // 👍 works with auto-refactoring.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment