5 TypeScript Utility Types That Make Your Code More Expressive

5 TypeScript Utility Types That Make Your Code More Expressive

Use TypeScript generics to write simpler, cleaner and easier to understand code

·

2 min read

If you’ve used TypeScript before then you know how powerful it can be.

It provides context that helps you understand how code should be used. TypeScript also sits right next to your business logic, so it self-documents the code. Leveraging TypeScript makes it easier to maintain your code and easier for other developers to understand your code.

Even if you're familiar with TypeScript, you might not know about some of the utility types that TypeScript has baked into it. These utility types transform existing types into new types for you. Your TypeScript code becomes simpler but more expressive.

Let's explore 5 utility types that can change the way you use TypeScript:

1. Partial

The Partial type makes all properties of a given type optional

// `A` and `B` are required
type BaseType = { A: string; B: string };

// `A` and `B` are now optional
// { A?: string | undefined; B?: string | undefined }
type PartialType = Partial<BaseType>;

2. Required

The Required type makes all properties of a given type required

// `A` and `B` are optional
type BaseType = { A?: string; B?: string };

// `A` and `B` are now required
// { A: string; B: string }
type RequiredType = Required<BaseType>;

3. Pick

The Pick type lets you choose specific properties from a given type

type BaseType = { A: string; B: string; C: string };

// Only `A` and `C` exist on the created type
// { A: string; C: string }
type PickType = Pick<BaseType, 'A' | 'C'>;

4. Omit

The Omit type lets you exclude specific properties from a given type

type BaseType = { A: string; B: string; C: string };

// Only `B` exists on the created type
// { B: string }
type OmitType = Omit<BaseType, 'A' | 'C'>;

5. NonNullable

The NonNullable type removes null or undefined from a given type

type BaseType = string | boolean | null | undefined;

// string | boolean
type NonNullableType = NonNullable<BaseType>;

Conclusion

These utility types might not seem like much, but they drastically reduce the amount of code you need to write.

They allow you to have a base type — a single source of truth — that can be extended in powerful ways. Having a single base type makes it easier to refactor. The easier it is to refactor, the easier it is to maintain.

If used correctly, they can make your workflow faster.