首页 > 解决方案 > 当您尝试将数组解构为对象时如何自动检测错误?

问题描述

有时,一种错误输入{}[]导致无法预料的错误并且难以调试。例如,此代码不会触发错误并将编译:

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: ... }

标签: typescripteslint

解决方案


推荐阅读