Variance — when a Dog[] may stand in for an Animal[]¶
Level: 301 · for TypeScript users who want to know why unsound code compiles
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: A Dog[] passes as an Animal[] because arrays are compared covariantly; parameters are compared the other way, so onlyDogs(d: Dog) is rejected for an (a: Animal) => void property (TS2322) but accepted for the same member written as a method, where it throws a TypeError.
Keywords: variance, covariance, contravariance, strictFunctionTypes
What the finished page will answer¶
- Why does
const animals: Animal[] = dogscompile, and what goes wrong onceanimalsis given aCat? - Why is
(d: Dog) => voidrejected for a property typed(a: Animal) => voidbut accepted for a method, and what does calling it with anAnimaldo? - Which way do return types vary: is
() => Dogassignable to() => Animal, and the reverse? - What do the
inandoutannotations on a type parameter declare, and why does TS2636 catch a wrongouton a property but not on a method? - What does
--strictFunctionTypes falsechange in the same file?
Examples it will need¶
-
variance_method_bivariance_sh.sh— tsc's TS2322 for the property-style handler only, then the TypeError that the accepted method-style handler throws -
variance_annotations_tserror.ts— TS2636 for anoutannotation on a type used as a parameter, and for aninannotation on a return type -
variance_return_types_ts.ts— a() => Dogused as a() => Animal, and what the caller receives
See also¶
- Array covariance — the array case, run until it breaks
- Function types — function types, whose parameters vary the other way
strict—strictFunctionTypes, one of the eight strict checks- Generic types — the type parameters that
inandoutannotate extendsandsuper— theextendsthat makes a Dog an Animal- Rust: When the type checker is wrong ↗ — what soundness means, from a checker that promises it