All quizzesHard
TypeScript Expert — Series 2
Preview — 3 of 10 questions
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 is typed the literal "a" — the const modifier on the type parameter tells TypeScript to infer the narrowest possible (literal) type for T from the argument, as if as const had been applied to it, instead of widening to string[]
Dresult's type is left as the unresolved expression readonly ["a","b","c"][0]
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 } — distributing the union across a function-*parameter* position (which is contravariant), then capturing it back via infer I, effectively flips the union into an intersection, because combining multiple contravariant constraints requires satisfying all of them simultaneously
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 — strictFunctionTypes specifically only tightens parameter checking for standalone function-*typed properties* (e.g. compare: (other: unknown) => number); method syntax (compare(other: unknown): number, as declared here) is deliberately exempted from that stricter check and remains checked bivariantly, allowing a narrower parameter type
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.