Type-Level Computation — Series 3

Preview — 3 of 10 questions

javascript
type Equals<A, B> =
  (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;

type Mutual<A, B> = A extends B ? (B extends A ? true : false) : false;

type X = Equals<{ a: 1 } & { b: 2 }, { a: 1; b: 2 }>;
type Y = Mutual<{ a: 1 } & { b: 2 }, { a: 1; b: 2 }>;
type Z = Mutual<any, string>;
AX is false, Y is true, Z is boolean
BX is true, Y is true, Z is true
CAll three are false
DCompile-time error — a generic function type may not appear on the checked side of a conditional

javascript
type Build<N extends number, A extends unknown[] = []> =
  A["length"] extends N ? A : Build<N, [...A, unknown]>;

type GT<A extends number, B extends number> =
  Build<A> extends [...Build<B>, ...infer R] ? (R extends [] ? false : true) : false;

type P = GT<5, 3>;
type Q = GT<3, 5>;
type R = GT<3, 3>;
AP is true, Q is true, R is true
BAll three are false — tuple patterns cannot express a length comparison
CP is true, Q is false, R is false
DCompile-time error — Build<B> may not be spread inside a pattern on the checked side

javascript
type F = ((a: string) => void) | ((a: number) => void);

type P = Parameters<F>;
A[a: string & number] — the parameters are intersected, as contravariance requires
B[a: string] | [a: number] — Parameters is a distributive conditional, so it is applied to each union member
C[a: unknown]
DCompile-time error — F does not satisfy Parameters's constraint, because a union of functions is not a function type

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.