typescript / expert
Snippet
Type-Level Covariance and Contravariance Checking for Test Harnesses
Advanced type-level testing utility that computes variance properties of function signatures. It asserts covariant return types and contravariant parameter acceptance strictly within TypeScript's type checker without runtime execution overhead.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
type IsSubtype<T, U> = T extends U ? true : false;type CheckCovariance<Fn, Producer> =Fn extends () => infer R ? IsSubtype<R, Producer> : false;type CheckContravariance<Fn, Consumer> =Fn extends (arg: infer A) => void ? IsSubtype<Consumer, A> : false;type CovariantTest = CheckCovariance<() => 'admin', string>;type ContravariantTest = CheckContravariance<(arg: string) => void, 'admin'>;
Breakdown
1
type IsSubtype<T, U> = T extends U ? true : false;
Evaluates subtyping relationships via conditional generic type constraint resolution.
2
Fn extends () => infer R ? IsSubtype<R, Producer> : false;
Extracts function return type R to verify covariance against expected Producer supertype.
3
Fn extends (arg: infer A) => void ? IsSubtype<Consumer, A> : false;
Extracts parameter type A to verify contravariance by checking if Consumer extends A.