I have developed a function that can add an item to an array or update an item at a specific index if provided.
Utilizing TypeScript, I have encountered a peculiar behavior that is puzzling me.
Here is the Playground Link.
This simple TypeScript function works without any issues:
function OKAddOrUpdateFunction(item: string, index?: number) {
const foo = index !== undefined
? Object.assign([], initialArray, { [index]: item }) : [...initialArray, item];
}
However, when I try to store whether the index
is defined or not in a const
for later use:
function NOKAddOrUpdateFunction(item: string, index?: number) {
const isIndexDefined = index !== undefined;
const foo = isIndexDefined
? Object.assign([], initialArray, { [index]: item }) : [...initialArray, item];
}
TypeScript throws an error specifically relating to the index within the Object.assign
:
(parameter) index: number | undefined
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.(2464)
The reason behind this error eludes me...