DAY 25 OF 30
Utility types: Partial, Required, Pick, Omit
Yesterday, in one sentence
Looking up the type of a property on an object type, written in square brackets
like Hero["name"]. The property name in the brackets is written as a type, and
passing a union of names gives a union of those property types.
Did you say:
- ✓looks up the type of a property on an object type
- ✓written in square brackets like `Hero["name"]`
- ✓a union of names gives a union of those property types
Interview question
Hero[keyof Hero] give you, and why?A union of the types of every property on Hero. keyof Hero gives a union of
the property names, and passing a union into an indexed access type gives a union
of those property types.
Did you say:
- ✓a union of the types of every property
- ✓`keyof Hero` gives a union of the property names
- ✓a union of names in an indexed access type gives a union of those types
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
Pick<Villain, "name" | "scheme"> here?
type Villain = {
name: string
scheme: string
level: number
}
Pick builds a new object type from only the properties you name. Omit<Villain, "level"> would give the same result here by removing the one you do not want.
Partial, Required, Pick and Omit do?Partial makes every property optional. Required makes every property
required. Pick builds a new object type from only the named properties.
Omit builds a new object type with the named properties removed.
Did you say:
- ✓`Partial` makes every property optional
- ✓`Required` makes every property required
- ✓`Pick` builds a new object type from only the named properties
- ✓`Omit` builds a new object type with the named properties removed