Typescript - Tips & Tricks - Literal Types

February 17, 2021

Last updated: September 9, 2021

122 words

Post contents

Welcome back! Today I show you the Literal Types.

This feature permits you to create a set of relationship values.

type Direction = "North" | "South" | "East" | "West";

Literal types in this case create also a Type Guard of your field, so the compiler can detect your errors or your typos.

let directionError: Direction = "east" // Type '"east"' is not assignable to type 'Direction'let direction: Direction = "East" // OK

You can create Literal Types from different types such as booleans, numbers, and strings, and you can combine together different types too.

type Valid = false | 0 | true | 1;

That's all for today See you soon guys!

Subscribe to our newsletter!

Subscribe to our newsletter to get updates on new content we create, events we have coming up, and more! We'll make sure not to spam you and provide good insights to the content we have.