Advanced Typescript

Get familiar with some of Typescript's greatest advanced features.

Kevin Kreuzer

--

Typescript is awesome. It offers so many great features. Here’s a summary of some of the greatest advanced Typescript features.

  • Union and intersection types
  • Keyof
  • Typeof
  • Conditional types
  • Utility types
  • Infer type
  • Mapped types

By the end of this blog post, you should have a base understanding of each of those operators and you should be able to use them in your projects.

Union and intersection types

Typescript allows us to combine multiple types to create a new type. This approach is similar to logical expressions in JavaScript where we can use the logical OR || or the logical AND && to create new powerful checks.

Union types

A union type is similar to Javascripts OR expression. It allows you to use two or more types (union members) to form a new type that may be any of those types.

We type the orderProduct method with a union type. TypeScript will throw an error once we call the orderProduct method with anything that is not a number or a string.

Intersection types

An intersection type, on the other hand, combines multiple types into one. This new type has all the features of the combined types.

The transferPlayer method accepts a type that contains all features of both Person and FootballPlayer. Only an object containing the name, firstname and the club property is valid.

Keyof

Now that we know the union type. Let’s have a look at the keyof operator. The keyof operator takes the keys of an interface or an object and produces a union type.

--

--

Kevin Kreuzer

Passionate freelance frontend engineer. ❤️ Always eager to learn, share and expand knowledge.