TypeScript · Senior · Question 51 of 75
Why does this compile, and what's the soundness hole?
const dogs: Dog[] = [];
const animals: Animal[] = dogs;
animals.push(new Cat());- ✓Correct answer: Arrays are treated covariantly for convenience, so writes through the wider type can put a
CatintoDog[] - 2It doesn't compile
- 3TypeScript copies the array on assignment
Explanation
Accepting readonly Animal[] in APIs that only read avoids the problem, since nothing can be written through it.