I have this base type:
export interface IMyType : {
field1: number,
field2: number
}
I also have this "extension" type:
export interface ISelectable {
isSelected: boolean;
}
Somewhere else, I have a function like this:
const foo = (param: (IMyType & ISelectable)[]) => { // <-- my on-the-fly "extended" type
param[0].isSelected = ... //do whatever
}
My problem is to created the composite array:
const dataArray: IMyType[] = [{field1: 0, field2: 0}, {field1: 0, field2: 0}];
const extendedArray = [ dataArray, ...[{isSelected: false}] ]; // <-- extend!
foo(extendedArray); // <-- PROBLEM! typescript still sees extendedArray
// as of type IMyType[] instead of
// (IMyType & Iselectable)[] so it refuses this.
I'm 99% sure that I misused the spread operator (...
) but right now I can't find the right syntax.
In recap, I tried the following :
const extendedArray = [ dataArray, ...[{isSelected: false}] ]; //Nope! (Makes zero sense, in the light of the comments below)
const extendedArray = [ ...dataArray, {isSelected: false} ]; //nope! (Makes zero sense, in the light of the comments below)
const extendedarray = dataArray.map (x => {isSelected: false, ...x}) //Almost correct but was missing sone syntactic sugar!
I've read this and many other answers but I can't figure it out : TypeScript add object to array with spread