Typescript - Tips & Tricks - Literal Types

Welcome back! Today I show you the Literal Types. This feature permits you to create a set of...

#typescript#webdev
Luca Del PuppoLuca Del Puppo
Article Series · Part 2 of 21TypeScript - Tips & Tricks
View full series (21)
  1. #1Previous
    typeof
  2. #2Reading now
    Literal Types
  3. #3Up next
    keyof
Browse all 21 parts in this series
  1. #1typeof
  2. #2Literal TypesCurrent
  3. #3keyof
  4. #4Union and Intersection
  5. #5Overloaded Functions
  6. #6this parameter
  7. #7any vs. unknown
  8. #8Optional modifier
  9. #9Index Signature
  10. #10readonly modifier
  11. #11Readonly Array
  12. #12Tuple
  13. #13Non-null assertion operator
  14. #14Never type
  15. #15Assert Function
  16. #16Type Guard
  17. #17Conditional Type
  18. #18infer keyword
  19. #19Mapped Types
  20. #20Advanced Types
  21. #21Rest Parameters & Rest Arguments

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!

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.