typescript / expert
Snippet
Explicit In/Out Variance Annotations for Type-Safe Subtype Compatibilities
Demonstrates explicit covariance (out) and contravariance (in) annotations on type parameters to speed up type-checking and guarantee subtype assignability.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type Animal = { name: string };type Dog = Animal & { breed: string };interface Container<out T> {get(): T;}interface Writer<in T> {put(item: T): void;}function processProducer(c: Container<Animal>): string {return c.get().name;}const dogContainer: Container<Dog> = { get: () => ({ name: "Rex", breed: "Shepherd" }) };const name = processProducer(dogContainer);
Breakdown
1
interface Container<out T> { get(): T; }
Annotates T as strictly covariant (produced output only), enabling Container<Dog> to assign to Container<Animal>.
2
interface Writer<in T> { put(item: T): void; }
Annotates T as strictly contravariant (consumed input only).
3
const name = processProducer(dogContainer);
Passes subtype container (Dog) where supertype container (Animal) is required safely.