Looking to overcome the habit of using any
in TypeScript, specifically when creating a function that adds or removes an item from an array. The key requirement is that the item must have an id
property of type string
. Here's how I currently have it implemented:
interface Item {
id: string;
[key: string]: any;
}
function toggleArrayItem(array: Item[], item: Item) {
const index = array.findIndex(i => i.id === item.id);
if (index >= 0) {
array.splice(index, 1);
} else {
array.push(item);
}
}
I've considered adjusting the third line to include a list of possible types such as
string | number | string[] | number[]
, but realized this isn't a viable solution. How can I rewrite this function without resorting to using any
?