0
0
Typescriptprogramming~5 mins

Union type syntax and behavior in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a union type in TypeScript?
A union type allows a variable to hold values of different types by combining multiple types with the | symbol. For example, string | number means the variable can be a string or a number.
Click to reveal answer
beginner
How do you declare a variable that can be either a number or a boolean?
You use a union type like this: <code>let value: number | boolean;</code>. This means <code>value</code> can hold a number or a boolean.
Click to reveal answer
intermediate
What happens if you try to use a union type variable without checking its type first?
TypeScript will show an error if you try to use properties or methods that are not common to all types in the union. You need to check the type first to safely use specific features.
Click to reveal answer
intermediate
Explain how TypeScript narrows union types with an example.
TypeScript narrows union types by checking the type at runtime. For example:<br>
if (typeof value === 'string') {<br>  // Here, value is treated as string<br>  console.log(value.toUpperCase());<br>} else {<br>  // Here, value is treated as number<br>  console.log(value.toFixed(2));<br>}
Click to reveal answer
beginner
Can union types include more than two types? Give an example.
Yes, union types can combine many types. For example: <code>let data: string | number | boolean;</code> means <code>data</code> can be a string, number, or boolean.
Click to reveal answer
Which symbol is used to create a union type in TypeScript?
A?
B&
C|
D:
What will TypeScript do if you try to call a method that exists only on one type in a union without checking the type first?
AAutomatically convert the type
BShow a type error
CIgnore the error
DRun the method anyway
How can you safely use a union type variable that could be a string or a number?
AUse a type check like typeof
BCall string methods directly
CAssign it to any type
DIgnore the type system
Which of these is a valid union type declaration?
Alet x: string | number;
Blet x: string & number;
Clet x: string, number;
Dlet x: string-number;
Can union types include custom types like interfaces?
AUnion types are only for arrays
BNo, only primitive types are allowed
COnly classes can be used in union types
DYes, union types can combine any types including interfaces
Describe how to declare and use a union type in TypeScript with an example.
Think about how a variable can hold a string or a number.
You got /3 concepts.
    Explain how TypeScript helps you safely work with union types using type narrowing.
    Consider how you check if a variable is a string before calling string methods.
    You got /3 concepts.