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());

Explanation

Accepting readonly Animal[] in APIs that only read avoids the problem, since nothing can be written through it.

Further reading

Problem with a question

TypeScript · Senior · question 51

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz