有时,一种错误输入{}
会[]
导致无法预料的错误并且难以调试。例如,此代码不会触发错误并将编译:
interface Item {
id: string;
}
interface State {
items: Item[];
}
const state: State = {
items: [],
};
const newItems: Item[] = [{ id: "123" }, { id: "234" }];
console.log(Array.isArray(state.items)); // true
// WTF??? no error
state.items = {
...state.items,
...newItems,
}
console.log(Array.isArray(state.items)); // false
// error, it is ok
state.items = {
0: {id: "val"},
};
但是在运行时,你会得到一个带有键的对象,而不是数组{0: ..., 1: ... }