Union Types
TypeScript union types allow us to combine individual types into flexible combinations.
StartKey Concepts
Review core concepts you need to learn to master this subject
TypeScript Union Type
TypeScript Union Type Syntax
TypeScript Union Type Narrowing
TypeScript Function Return Union Type
TypeScript Union of Array Types
TypeScript Union Type Common Property Access
TypeScript Union of Literal Types
TypeScript Union Type
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.
- 1TypeScript 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…
- 2Unions 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…
- 3Typing 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) { // ….
- 4One 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 …
- 5Unions 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 …
- 6When 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…
- 7We 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🙌 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
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory