All quizzesEasy
Generic Basics
Preview — 3 of 10 questions
What is the type of result here?
javascript
function identity<T>(value: T): T {
return value;
}
const result = identity("hello");Aunknown
Bstring — TypeScript infers T = string from the argument
Cany
DT
Which of these is the correct way to type a function that returns the first element of any array?
javascript
// Option A:
function first(arr: any[]): any { return arr[0]; }
// Option B:
function first<T>(arr: T[]): T { return arr[0]; }
// Option C:
function first(arr: unknown[]): unknown { return arr[0]; }AOption A — any[] is most flexible
BOption B — generic preserves the element type
COption C — unknown is safest
DAll three are equivalent
What does TypeScript infer for T and U?
javascript
function pair<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
const result = pair("hello", 42);
// result: ?A[T, U]
B[any, any]
C[string, number]
Dstring | number
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.