All quizzesHard
TypeScript Expert — Series 2
Preview — 3 of 10 questions
What type does TypeScript infer for result?
javascript
function first<const T extends readonly unknown[]>(arr: T): T[0] {
return arr[0];
}
const result = first(['a', 'b', 'c']);Aresult is typed string — the const modifier on the type parameter has no effect on how T is inferred here
BCompile-time error — const can't be applied to a type parameter, only to variable declarations
Cresult has literal type "a" because const inference preserves the tuple.
Dresult's type is left as the unresolved expression readonly ["a","b","c"][0]
What type does Result resolve to?
javascript
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
type Result = UnionToIntersection<{ a: string } | { b: number }>;AResult is { a: string } | { b: number }, unchanged
BResult is never
CCompile-time error — infer can't be used to extract a function's parameter type
DResult is { a: string } & { b: number }.
With strictFunctionTypes: true enabled, does Money's compare (parameter narrowed to Money instead of unknown) satisfy Comparator?
javascript
interface Comparator {
compare(other: unknown): number;
}
class Money implements Comparator {
constructor(public cents: number) {}
compare(other: Money): number { return this.cents - other.cents; }
}AYes. The method syntax keeps parameter checks bivariant under strictFunctionTypes.
BNo — strictFunctionTypes makes all function-parameter checks strictly contravariant, everywhere, with no exceptions, and Money's narrower parameter type is rejected
CNo — methods and properties are checked completely identically under strictFunctionTypes
DYes, but only because Money is a class — the same code would fail if Comparator were implemented via a plain object literal instead
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.