Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Spread operator" syntax

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Bu using the spread operateor you appened elements, you do not modify the existing ones

So
const extendedArray = [ dataArray, ...[{isSelected: false}] ];

The extendedArray will have two type elements:
First element will be an array of IMyType , the second element will be of type { isSelected: boolean }

If you want to modify all elements in an array – use .map(). And preferably create a copy of all objects like this:

const extendedArray = dataArray.map(item => { return { ...item, isSelected: false } });

//All is ok now
foo(extendedArray);

Playground here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading