Skip to content

Instantly share code, notes, and snippets.

@kamauwashington
Last active September 4, 2022 23:32
Show Gist options
  • Save kamauwashington/c80f0b2e317c87d19bc09476f1a706e2 to your computer and use it in GitHub Desktop.
Save kamauwashington/c80f0b2e317c87d19bc09476f1a706e2 to your computer and use it in GitHub Desktop.

TypeScript Bits

Literal Types / Type Guards

TypeScript Bits are small, easily digestible pieces of information to encourage TypeScript/JavaScript best practices. From beginner, to intermediate, to ninja, these bits are for you 😄


Estimated reading time : 2 minutes

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 :

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

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

type CardinalDirection = "North" | "South" | "East" | "West";

function whichWay() : CardinalDirection {
  return "N"; // Type '"N"' is not assignable to type 'CardinalDirection'.(2322)
}

Example 3

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment