DEV Community

Cover image for Typescript - Tips & Tricks - Literal Types
Luca Del Puppo for This is Learning

Posted on • Edited on

5 2

Typescript - Tips & Tricks - Literal Types

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";
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

That's all for today
See you soon guys!

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay