2 min read Intermediate September 5th, 2022
Literal Types / Type Guards
When using TypeScript, we often (and hopefully as a manner of practice, always) declare the type of a variable or property. TypeScript allows the possibility of a variable or property to be of one or more types. This means that a variable or property can be either a number, string, or custom type by declaring it like so :
typescript
let myVariable : number | string | ICustomType;The interesting part is that this can be done with primitives, mixed primitives, and types for variables, properties, and functions!
Example 1
typescript
type TennisScore = "love" | 15 | 30 | 40 | "all" | "deuce" | "ad-in" | "ad-out";
let score : TennisScore = 30; // allowed
score = "love"; // allowed
score = 1;// Type '1' is not assignable to type 'TennisScore'.(2322)Example 2
typescript
type CardinalDirection = "North" | "South" | "East" | "West";
function whichWay() : CardinalDirection {
return "N"; // Type '"N"' is not assignable to type 'CardinalDirection'.(2322)
}Example 3
typescript
type CardinalDirection = "North" | "South" | "East" | "West";
type CardinalDirectionShorthand = "N" | "S" | "E" | "W";
function whichWay() : CardinalDirection | CardinalDirectionShorthand {
return "N"; // allowed
}Notes
- IMPORTANT this feature is NOT the same as runtime validation. This is often called “Narrowing” in scripting languages, which takes a loosely defined value, and narrows the possibilities of types and or primitives to defined constraints.
- Literal types can be used to return one or more types, or pass one or more types of values to and from a function.
- There is awesome intellisense support, notifying individuals working in a codebase what values or types are possible.
- if..then logic will only allow comparison with values or types defined (with intellisense guidance as well). The exception is the else statement.
Visit the TypeScript Documentation on Literal Types for more in-depth information!