All quizzesHard
Conditional Types & Infer — Series 2
Preview — 3 of 10 questions
javascript
type IsString<T> = T extends string ? 'yes' : 'no';
type A = IsString<string>;
type B = IsString<number>;
type C = IsString<any>;AC is 'no', since any doesn't extend string
BC is any, since conditional types simply pass any straight through, unresolved
CCompile-time error — any can't be used as a type argument for a conditional type
DC is 'yes' | 'no' — any is handled as a special case inside conditional types: instead of resolving to a single branch, the compiler immediately produces the union of both possible branches, reflecting the fact that the actual underlying type is genuinely unknown
javascript
type Repeat<T, N extends number, Acc extends unknown[] = []> =
Acc['length'] extends N ? Acc : Repeat<T, N, [...Acc, T]>;
type ThreeStrings = Repeat<string, 3>;
const x: ThreeStrings = ['a', 'b', 'c'];AThreeStrings is the general type string[]
BCompile-time error — a tuple type can't be recursively constructed based on a numeric type parameter
CThreeStrings is the tuple [string, string, string] — the recursive type keeps appending one more T to the accumulator tuple Acc, checking its length against N after each step, stopping once they match
DThreeStrings simplifies to just string, since Repeat collapses to a single element
javascript
type Boxed<T extends readonly unknown[]> = { [K in keyof T]: { value: T[K] } };
type Original = [string, number, boolean];
type BoxedTuple = Boxed<Original>;
const b: BoxedTuple = [{ value: 'a' }, { value: 1 }, { value: true }];ABoxedTuple is the tuple [{ value: string }, { value: number }, { value: boolean }] — mapping over keyof T when T is a tuple preserves the tuple's exact length and each position's specific type, rather than collapsing into a general array
BBoxedTuple is { value: string | number | boolean }[], a regular array
CCompile-time error — mapped types can only be applied to plain object types, never to tuple types
DBoxedTuple is { value: T }[], with T left unresolved as a placeholder
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.