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