keyof and utility types

7.0.2

Derive related types from the original type to keep field names consistent.

On this page

Allow only real field names

keyof makes a union of the keys of a type. With a generic constraint, the caller can only supply a key that belongs to the object. T[K] gives the type of that property.

function readField<T, K extends keyof T>(row: T, key: K): T[K] {
  return row[key];
}

const price = readField({ name: "Pen", price: 2 }, "price");

Describe a view or a patch

Pick selects fields. Omit removes fields. Partial makes fields optional at the top level. These types describe values for the compiler. They do not remove fields from runtime objects.

type Product = { id: number; name: string; price: number };
type ProductCard = Pick<Product, "name" | "price">;
type ProductUpdate = Partial<Omit<Product, "id">>;

Official references