TypeScript 允许我们使用超类型的变量(TypeScript 数组是协变的)为数组类型的变量添加别名:
const nums: number[] = [];
const things: (number | string)[] = nums;
things.push("foo");
nums[0] *= 3;
console.log(nums[0]); // `NaN` !!
Run Code Online (Sandbox Code Playgroud)
为什么?这似乎是保护我们免受运行时错误的好地方。鉴于 Java 因具有协变数组而被嘲笑,这似乎是一个有意的 TS 功能。
这是其他人在过时的 TypeScript 问题上提出的问题,但我没有看到任何答案。
typescript ×1