Skip to content

Instantly share code, notes, and snippets.

@KROSF
Last active March 6, 2020 14:27
Show Gist options
  • Save KROSF/9614b51105028808f0b3095ea8b5417a to your computer and use it in GitHub Desktop.
Save KROSF/9614b51105028808f0b3095ea8b5417a to your computer and use it in GitHub Desktop.
Typescript Tips && Tricks

Typescript Tips && Tricks

Recursive Partial

type RecursivePartial<T> = { [P in keyof T]?: RecursivePartial<T[P]> };

Type Guards

type Student = {
  name: string
}

type Professor = {
  name: string
  salary: number
}

type Person = Student | Professor

const isProfessor = (person: Person): person is Professor => 'salary' in person

Pick & Omit

type Person = {
  name: string
  address: string
  age: number
}

type NameAndAddress = Pick<Person, 'name' | 'address'>

type NamelessPerson = Omit<Person, 'name'>

Admit only valid properties as input and emit correct type

type Person = {
  name: string
  address: string
  age: number
}

const getProperty = <O, P extends keyof O>(obj: O, prop: P): O[P] => obj[prop]

Typing literal object values and infer keys

interface Route {
  path: string
  name: string
}

const createRoutes = <T extends object>(
  routes: Record<keyof T, Route>,
): Record<keyof T, Route> => routes

// const routes: Record<"key1" | "key2", Route>
const routes = createRoutes({
  key1: {
    path: 'key1',
    name: 'Key1',
  },
  key2: {
    path: 'key2',
    name: 'Key2',
  },
})

source

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