Key Concepts

Review core concepts you need to learn to master this subject

TypeScript Union Type

let answer: any; // any type let typedAnswer: string | number; // union type

TypeScript allows a flexible type called any that can be assigned to a variable whose type is not specific. On the other hand, TypeScript allows you to combine specific types together as a union type.

Union Types
Lesson 1 of 1
  1. 1
    TypeScript lets us type variables with different levels of type specificity. If we want to enforce that a variable is a string, we can type it as a string. This type is very specific since TypeSc…
  2. 2
    Unions allow us to define multiple allowed type members by separating each type member with a vertical line character |. With a union, we can re-type the program from the previous exercise like t…
  3. 3
    Typing with unions gives us more flexibility with type specificity, but there’s also more to consider. For instance, look over this union: function getMarginLeft(margin: string | number) { // ….
  4. 4
    One of the awesome things about TypeScript is that it’s able to infer types in many cases so that we don’t have to manually write them. A great example is a function’s return type. TypeScript will …
  5. 5
    Unions are even more powerful when used in combination with arrays. For instance, we can represent time in TypeScript with a number or a string type. If we had a list of dates in both types, we’d …
  6. 6
    When we put type members in a union, TypeScript will only allow us to use the common methods and properties that all members of the union share. Take this code: const batteryStatus: boolean | numb…
  7. 7
    We can use literal types with TypeScript unions. Literal type unions are useful when we want to create distinct states within a program. For instance, if we were writing the code that controlled …
  8. 8
    🙌 Way to go! We’ve learned a variety of ways to create types that are as specific as we need with unions. To recap, we’ve learned: - We can combine two types with a vertical bar character |. This …

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo