TypeScript TypeScript Type System & Generics 1 — Questions and Answers
Question 1: What keyword is used to define a generic type parameter in TypeScript?
- type
- generic
- T (angle bracket syntax) (Correct answer)
- var
Correct answer: T (angle bracket syntax)
TypeScript generics use angle bracket syntax (e.g., <T>) to define a type parameter that can be substituted at call or instantiation time.
Question 2: Which TypeScript type represents a value that can be any type and opts out of type checking?
- unknown
- never
- any (Correct answer)
- void
Correct answer: any
The `any` type disables TypeScript's type checking for a variable, allowing it to hold any value without compile-time errors.
Question 3: What is the difference between `unknown` and `any` in TypeScript?
- They are identical
- `unknown` requires a type check before use; `any` does not (Correct answer)
- `any` requires a type check before use; `unknown` does not
- `unknown` only works with primitives
Correct answer: `unknown` requires a type check before use; `any` does not
`unknown` is the type-safe counterpart of `any` — you must narrow it (e.g., with typeof or instanceof) before performing operations on it.
Question 4: Which utility type makes all properties of a type optional?
- Required<T>
- Readonly<T>
- Partial<T> (Correct answer)
- Pick<T, K>
Correct answer: Partial<T>
`Partial<T>` constructs a type with all properties of T set to optional, meaning each property may or may not be present.
Question 5: What does the `never` type represent in TypeScript?
- A value that is undefined
- A value that is null
- A type with no possible values, such as the return of a function that always throws (Correct answer)
- An optional parameter
Correct answer: A type with no possible values, such as the return of a function that always throws
`never` represents the type of values that never occur, commonly used as the return type of functions that always throw or run infinitely.
Question 6: Which of the following correctly applies a generic constraint in TypeScript?
- function fn<T>(x: T) where T extends object
- function fn<T extends object>(x: T) (Correct answer)
- function fn<T: object>(x: T)
- function fn<T implements object>(x: T)
Correct answer: function fn<T extends object>(x: T)
Generic constraints use the `extends` keyword inside the angle brackets, e.g., `<T extends object>`, to restrict which types can be substituted for T.
What keyword is used to define a generic type parameter in TypeScript?