How to automatic detect mistakes when you try to destructurize an array into object?

Viewed 48

Some times one mistype {} instead of [] causes unexpacted errors and hard to debug. For example this code will not trigger errors and will compile:

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"},
};

But in runtime, you will get an objects, instead of array, with keys {0: ..., 1: ... }

0 Answers
Related