typescriptadvanced
TypeScript Generics
Generic functions, generic constraints and conditional types
7 questions
By EZ4Code Team
1. Which of the following generic function signatures is correct?
function identity<T>(arg: T): T {
return arg
}function identity<T>(arg: T): T
function identity(T arg): T
function identity<T>(arg: any): any
function identity(arg: T): T
Explanation: Generics use <T> to declare a type parameter, used in parameters and return values to ensure input and output types match.
2. What is the purpose of using extends to constrain generics?
Restricts the type parameter to satisfy a certain structure (have certain properties)
Implements inheritance
Declares class inheritance
Creates an abstract class
Explanation: T extends Constraint restricts the type parameter to be the specified type or its subtype, often used to require an object to have certain properties.
3. What is the result of keyof T in the following code?
type T = { a: number; b: string }
type K = keyof T // 'a' | 'b'A union of all property names of T: 'a' | 'b'
The type of all property values of T
T itself
any
Explanation: keyof T gets a union of all keys of type T; for {a:number;b:string} the result is 'a' | 'b'.
4. What does the conditional type T extends U ? X : Y mean?
If T is assignable to U, the type is X, otherwise Y
T inherits from U
T equals U
T and U form a union
Explanation: Conditional types select type X or Y based on whether T is assignable to U, often combined with infer to extract types.
5. What is the infer keyword used for?
Inferring and extracting a type variable within a conditional type
Declaring a variable
Declaring a constant
Type assertion
Explanation: infer R declares a type variable R to be inferred within the extends clause of a conditional type, often used to extract function return types, array element types, etc.
6. Which is a built-in utility type used to extract a function's return type?
ReturnType<T>
Parameters<T>
Partial<T>
Pick<T,K>
Explanation: ReturnType<T> extracts the return type of function type T; Parameters extracts the parameter tuple; Partial/Pick are object utility types.
7. What is the syntax for generic default types?
function create<T = string>(): T[] { return [] }<T = string>
<T: string>
<T as string>
<T string>
Explanation: Generic default types are specified with <T = DefaultType>, used when no type argument is explicitly provided.