OpenSesame Engineering Blog

TypeScript Utility Types in React

by Nick Bernard | May 17, 2022

Tools on workbench

If you’ve been writing TypeScript for any amount of time, you’ve probably ran across some of the language’s built-in utility types.

Record

The Record type essentially represents an object.

Partial

The Partial type makes all properties of a type optional. This is particularly useful for creating mock objects for testing. You can create a factory function that uses the desired type without needing to provide every value:

const createMockProfile = ({
  name: 'Mock User',
  avatar: 'test.jpg'
}: Partial<Profile>): Profile => ({
  name,
  avatar,
});

const testProfile = createMockProfile({ name: 'Test User' }); 

console.log(testProfile); // { name: 'Test User', avatar: 'test.jpg' }

The opposite of Partial is Required.

Pick and Omit

Try these out in the TypeScript Playground.


© 2022 OpenSesame