More advanced type syntaxes for another day

(A veryfast reference overview below. Don't worry if you don't understand something, just know that those exist, so you can research later.)

  • Mapped types is a syntax used to declare generic objects.

type GenericObject = {
    requireMe: number
    [k: string]: any
}
// GenericObject CAN have any property and MUST have `requireMe`
  • Mapped types can be used to remap one object type to another, by iterating over its keys.

  • keyof lists all possible keys of an object type as a type union;

type Dummy = {
    a: string
    b: number
}
type Mapped = {
    [k in keyof dummy]: { value: dummy[k] }
}
// wraps Dummy's values into a { value: x } object
  • Properties may me accessed with [""]

type X = Dummy['a'] //will return `string`
  • Conditional types were created to solve a dozen of the type system's limitations. Its name may be misleading. One of the dozen things conditional types can do is to "pick" a type from inside another type expression. For instance:

type Unwrap<T> = T extends Promise<infer R> ? R : never
type X = Unwrap<Promise<number>>  // X will be 'number'
// this sample also uses generics, which we will cover soon
  • The standard type lib includes some auxiliary type aliases like Record and Omit. All of those type aliases are made by composing the features previously shown. You can check all available helpers and its implementation by CTRL+Clicking any of them.

type DummyWithoutA = Omit<Dummy, 'a'>

When you want to dig deeper, I'd strongly recommend checking the Typescript playground samples session.

Last updated