Samantha J T Star
Samantha J T Star

Reputation: 32798

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?

Upvotes: 0

Views: 737

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

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.

Upvotes: 3

Related Questions