TypeScript Utility Types

You can see examples in the pictures and more demo codes in the rest of post.

Type Inference

ConstructorParameters<T>

Syntax

Examples

InstanceType<T>

Syntax

Examples

ReturnType<T>

Syntax

Examples

Parameters<T>

Syntax

Examples

NonNullable<T>

Syntax

Examples

Extract<T, U>

Syntax

Examples

Exclude<T, U>

Syntax

Examples

Demo 1

Demo 2

As you can see in the following screenshot, hovering with mouse cursor on PersonWithOnlyString Type Alias, VSCode shows intellisense. It means that Pick<T> Utility Type created a new Type Alias like interface with 3 fields.

Notice that many features like Type Alias, Union Types, Literal Types, Mapped Types etc. in TypeScript are valid in compile-time not run-time. It means that let's say you created a Type Alias with three fields and write code according to this type, but if you try to remove one of the three fields in object in run-time, there will not be any exception or error in the application.

As a result, we create these features to help TypeScript compiler.

Demo 3

Notice that Pick<T> and Partial<T> are used together in the following demo.

Partial<T> looks like following screenshot in the compile-time. Notice that every field in PartialPersonWithOnlyString type can be assigned undefined.

Demo 4

Notice that Pick<T> Utility Type is used with my custom FilterType Type Alias. The aim is creating a new sub type from Person interface. But, this time I didn't want to create a new sub type according to field name, new subtype is created according to field type. As you can see in the following screenshot, SubType<Person, string> created a new Type Alias with string fields.

Leave a Reply