Samantha J Samantha J - 4 months ago 9
TypeScript Question

How can I assign values to an array in a constructor using Typescript?

Here is what I have tried:

class PhraseService

phrasePosShortNames: [{ id: number, name: string }];
phrasePosNames = [
{
id: 0,
longName: '#',
shortName: '#'
},
{
id: 1,
longName: 'Noun',
shortName: '#'
},
{
id: 2,
longName: 'Verb',
shortName: 'V'
}
];
constructor( ) {

this.phrasePosShortNames = this.phrasePosNames.map(item => {
id: item.id,
name: item.longName
})
}


But this gives me an error:


Severity Code Description Project File Line Suppression State
Error TS2322 Type 'void[]' is not assignable to type '[{ id: number;
name: string; }]'. Property '0' is missing in type 'void[]'


Can someone tell me what I'm doing wrong?

Answer
this.phrasePosNames.map(item => {
    return {
      id: item.id,
      name: item.longName
    };
});

And the type should be

{ id: number, name: string }[]

or

Array<{ id: number, name: string }>

I would define an interface instead, which would make the code more readable.