0
0
Typescriptprogramming~5 mins

Type alias for unions in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a type alias in TypeScript?
A type alias gives a new name to a type. It helps make code easier to read and reuse by naming complex types.
Click to reveal answer
beginner
How do you create a union type alias in TypeScript?
Use the type keyword followed by a name, then an equals sign, and list types separated by |. For example: type MyUnion = string | number;
Click to reveal answer
beginner
What does the union type string | number mean?
It means a value can be either a string or a number. The value must match one of the types in the union.
Click to reveal answer
intermediate
Why use a type alias for unions instead of writing the union everywhere?
It makes code cleaner and easier to update. If the union changes, you only update the alias once instead of many places.
Click to reveal answer
intermediate
Can type aliases be used with complex unions like objects and primitives?
Yes! You can create aliases for unions of any types, including objects, primitives, or even other type aliases.
Click to reveal answer
Which syntax correctly defines a type alias for a union of string and number?
Atype MyType = string & number;
Balias MyType = string & number;
Calias MyType = string | number;
Dtype MyType = string | number;
What does the union type alias type Status = 'success' | 'error' | 'loading'; represent?
AA value that can be any string
BA value that must be exactly 'success', 'error', or 'loading'
CA value that can be a number or string
DA value that is always a boolean
Why might you use a type alias for a union type?
ATo simplify code and make it easier to update
BTo make the code harder to read
CTo repeat the same union everywhere
DTo avoid using unions
Which of these is NOT a valid union type alias?
Atype Data = string & number;
Btype Option = boolean | null;
Ctype Status = 'open' | 'closed';
Dtype Result = string | number;
Can a type alias for a union include other type aliases?
AOnly if they are primitive types
BNo, type aliases cannot be nested
CYes, type aliases can be combined in unions
DOnly if they are interfaces
Explain what a type alias for a union is and why it is useful in TypeScript.
Think about naming a group of types together.
You got /3 concepts.
    Write a simple example of a type alias for a union of string literals representing colors.
    Use single quotes for string literals.
    You got /3 concepts.