typescript - 当您尝试将数组解构为对象时如何自动检测错误?
问题描述
有时,一种错误输入{}
会[]
导致无法预料的错误并且难以调试。例如,此代码不会触发错误并将编译:
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: ... }
解决方案
推荐阅读
- android-studio - 更改 Android Studio 预览窗口的默认缩放
- apple-watch - 在 watchOS 中请求位置及其对电池的影响
- django - Djagno:如何将电子邮件作为字典中的键传递给模板
- c# - 返回空字符串而不是 Null
- javascript - Ember 3.2.2 未将请求路由到 .NET Core 2.1 JSON Web API
- r - 如何在基地R中绘制带有南中国海的中国地图
- mysql - 每天列出每个类别中最畅销的商品,包括总销量和收入
- angular - Angular DataTables:$(...).DataTable 不是函数
- javascript - 闭包javascript中的嵌套for循环问题
- google-apps-script - 有没有办法在谷歌脚本中捕捉电子表格标题的变化?