What does 'variance' mean for generic types, and why does TypeScript's structural typing make some generic assignments unsound by default?
Short answer
Variance describes how subtyping relationships between type parameters affect subtyping of the generic type itself — TypeScript's structural, method-bivariant checking (for backward JS compatibility) allows some generic function parameter assignments that are technically UNSOUND…
Advertisement
AModel answer
Variance describes how subtyping relationships between type parameters affect subtyping of the generic type itself — TypeScript's structural, method-bivariant checking (for backward JS compatibility) allows some generic function parameter assignments that are technically UNSOUND (could cause a runtime type error) purely for practical ergonomic reasons, unlike stricter languages that enforce full soundness.
interface Animal { name: string; }
interface Dog extends Animal { breed: string; }
type Handler<T> = (item: T) => void;
let dogHandler: Handler<Dog> = (dog) => console.log(dog.breed);
let animalHandler: Handler<Animal> = dogHandler; // allowed, but technically unsound if called with a non-Dog AnimalReal-world example
Understanding a subtle class of bugs that TypeScript's structural type system deliberately permits for practical flexibility.
Likely follow-ups
- How does the 'strictFunctionTypes' compiler option change this bivariance behavior for standalone function types?
Related topics