typescript / beginner
Snippet
Literal Types
Literal types allow you to specify the exact value a string, number, or boolean must have, rather than just any value of that type.
snippet.ts
1
2
3
let response: "yes" | "no";response = "yes"; // Success// response = "maybe"; // Error: Type '"maybe"' is not assignable
Breakdown
1
let response: "yes" | "no";
Defines a variable that can only hold the exact string 'yes' or 'no'.
2
response = "yes";
Assigns a valid literal value to the variable.