TypeScript Has Several Utility Types To Map Types To Other Types

TopicSource
๐Ÿฆ’ TypeScriptTypeScript: Documentation - Utility Types

When you want to build a type that somehow depends on another, already existing, type, there are several utility types that can help you to build subsets with specific behaviors.

For example, you can use Partial<Type> to create a new type, where all properties of Type are optional, Readonly<Type> to make all properties readonly, Record<Type, Keys> to create a dictionary of the Type and define the desired keys, or Pick<Type, Keys> to create a subset of another type, only consisting of the given types.

There are many more, that can be looked up in the TypeScript: Documentation - Utility Types.

interface Person {
  firstName: string;
  lastName: string;
  age: number;
}

const getPerson = function (): Readonly<Person> {
  const person: Partial<Person> = {
    firstName: 'Jane',
    lastName: 'Doe'
  };

  person.age = 37;

  return person as Readonly<Person>;
};

const person = getPerson();

console.log(person.firstName);

type PersonCommandingRespect = Pick<Person, 'lastName' | 'age'>
const personCommandingRespect: PersonCommandingRespect = {
  lastName: 'Scully',
  age: 30
};



type PersonCommandingRespect2 = Omit<Person, 'firstName'>
const personCommandingRespect2: PersonCommandingRespect2 = {
  lastName: 'Scully',
  age: 30
};

  1. Defining union types