TypeScript TypeScript Type System & Generics 2 — Questions and Answers
Question 1: What is a union type in TypeScript?
- A type that is both A and B simultaneously
- A type that can be one of several specified types (Correct answer)
- A merged interface
- A type alias for a class
Correct answer: A type that can be one of several specified types
A union type (written as `A | B`) allows a variable to hold a value of type A or type B, enabling flexible yet type-safe code.
Question 2: What is an intersection type in TypeScript?
- A type that can be one of several types
- A type that combines multiple types into one, requiring all properties (Correct answer)
- A type that removes properties from another type
- A type only used with generics
Correct answer: A type that combines multiple types into one, requiring all properties
An intersection type (written as `A & B`) combines multiple types so the resulting type has all properties of A and all properties of B.
Question 3: Which utility type constructs a type by picking a set of properties from another type?
- Omit<T, K>
- Exclude<T, U>
- Pick<T, K> (Correct answer)
- Extract<T, U>
Correct answer: Pick<T, K>
`Pick<T, K>` creates a new type by selecting only the specified keys K from type T, effectively narrowing the shape.
Question 4: What does `Readonly<T>` do in TypeScript?
- Prevents a class from being extended
- Makes all properties of T immutable after assignment (Correct answer)
- Removes all methods from T
- Makes T only usable at compile time
Correct answer: Makes all properties of T immutable after assignment
`Readonly<T>` constructs a type with all properties of T marked as `readonly`, preventing reassignment after object creation.
Question 5: In TypeScript, what is a literal type?
- A type inferred from a literal value like `42` or `'hello'` (Correct answer)
- A type defined in a .d.ts file
- A type that wraps a primitive
- A type only used in switch statements
Correct answer: A type inferred from a literal value like `42` or `'hello'`
Literal types restrict a variable to one specific value, such as `type Direction = 'left' | 'right'`, providing extremely precise type constraints.
Question 6: What is type narrowing in TypeScript?
- Casting a type to a narrower interface
- Reducing a union type to a more specific type within a conditional block (Correct answer)
- Removing generics from a type
- Converting a class to a plain object
Correct answer: Reducing a union type to a more specific type within a conditional block
Type narrowing uses runtime checks (like `typeof`, `instanceof`, or `in`) to let TypeScript infer a more specific type inside a conditional branch.
What is a union type in TypeScript?