Want a faster signal before interviews? Take the Interview Ready Check →

DAY 25 OF 30

Utility types: Partial, Required, Pick, Omit

Yesterday, in one sentence

What is an indexed access type in TypeScript?

Interview question

What does Hero[keyof Hero] give you, and why?

TypeScript ships with some ready made generic typesGeneric Type that build a new type from one you already have. These are called utility types.

Partial<T> makes every property optional.

type Hero = {
  name: string;
  level: number;
  power: string;
};

type PartialHero = Partial<Hero>;
// { name?: string; level?: number; power?: string }

Required<T> does the opposite, and makes every optional property required.

type Draft = {
  name?: string;
  level?: number;
};

type FullHero = Required<Draft>;
// { name: string; level: number }

Pick<T, K> lets you pick which properties you want on the new object type. K is for key, and it is a literal unionLiteral Union of the property names you want on the new type.

type HeroSummary = Pick<Hero, "name" | "level">;
// { name: string; level: number }

Omit<T, K> is the opposite, and builds a new object type with the properties named in K removed.

type HeroWithoutPower = Omit<Hero, "power">;
// { name: string; level: number }

None of these change Hero. Each one produces a new type, and the original is untouched.

Check yourself

What is Pick<Villain, "name" | "scheme"> here?
type Villain = {
  name: string
  scheme: string
  level: number
}
What do the utility types Partial, Required, Pick and Omit do?