0
0
Typescriptprogramming~5 mins

Why union types are needed in Typescript - Quick Recap

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, like a choice between multiple types.
Click to reveal answer
beginner
Why do we need union types instead of just one type?
Because sometimes a value can be more than one type, like a number or a string, and union types let us handle that safely.
Click to reveal answer
intermediate
How do union types help prevent errors?
They make sure you only use the allowed types and force you to check which type you have before using it, avoiding mistakes.
Click to reveal answer
beginner
Give an example of a union type in TypeScript.
Example: let value: number | string; means value can be a number or a string.
Click to reveal answer
beginner
What real-life situation is similar to union types?
Like a key that can open either your house or your car. You have one key but it works for two things, just like one variable can hold two types.
Click to reveal answer
What does a union type allow in TypeScript?
ANo types at all
BA variable to hold multiple types
COnly one fixed type
DOnly string types
Which symbol is used to define a union type?
A|
B;
C:
D&
Why should you check the type of a union variable before using it?
ATo avoid runtime errors
BTo make code slower
CTo ignore type safety
DTo delete the variable
Which of these is a valid union type declaration?
Alet x: number & string;
Blet x: number string;
Clet x: number | string;
Dlet x: number/string;
What problem do union types solve?
AForcing variables to be undefined
BMaking variables only one type
CRemoving types completely
DAllowing variables to hold multiple possible types
Explain why union types are useful in TypeScript with an example.
Think about variables that can hold more than one type.
You got /3 concepts.
    Describe how union types help prevent errors in your code.
    Consider what happens if you use a variable without knowing its type.
    You got /3 concepts.