menu
299 tokens

Type Operators

Type inference and static term evaluation are one and the same.

Type Operators

Keys

1type User = { name: string; age: int32 };2type Keys = keyof User;3 4declare const key: Keys;

Indexed Access

1type User = { name: string; age: int32 };2type Name = User["name"];3 4declare const name: Name;

Intersections

1type Named = { name: string };2type Aged = { age: int32 };3type Person = Named & Aged;4 5declare const person: Person;6const name = person.name;7const age = person.age;

Conditional Types

1type Select<T> = T extends string ? "yes" : "no";2type Text = Select<string>;3type Number = Select<int32>;4 5declare const text: Text;6declare const number: Number;

Inference

1type Box<T> = { value: T };2type Unbox<T> = T extends Box<infer U> ? U : never;3type Value = Unbox<Box<"ready">>;4 5declare const value: Value;

Mapped Types

  • TS algebra is actually great for doing light metaprogramming
  • want to preserve as much of it as possible
  • thankfully, it's actually mostly sound already
  • especially once we agree that structural types are exact / fixed, and interfaces are dynamic
1export type Record<K: PropertyKey, V> = {2    [P in K]: V;3};

Utility Types

  • utility types!
  • mapped types
  • Pick, Readonly, ...
  • ThisParameterType
  • .. all the other utility types