Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source has X element(s) but target allows only 1

The typescript compile show this error:

Source has X element(s) but target allows only 1.

export const FooMapping: [{id: FooOperation, display: string}] = [
    { id: FooOperation.Undefined, display: 'Nothing' },
    { id: FooOperation.A, display: 'I'm A' },
    { id: FooOperation.B, display: 'I'm B' }
];

export enum FooOperation {
    Undefined = 0,
    A = 1,
    B = 2,
}

What is the correct way to define an array of special object of {id: FooOperation, display: string}?

like image 575
Shahar Shokrani Avatar asked Oct 11 '20 20:10

Shahar Shokrani


2 Answers

[{id: FooOperation, display: string}] defines a tuple of exactly one element.

Try:

export const FooMapping: Array<{id: FooOperation; display: string}> = [
    { id: FooOperation.Undefined, display: 'Nothing' },
    { id: FooOperation.A, display: "I'm A" },
    { id: FooOperation.B, display: "I'm B" }
];

Or think about something like:

interface Foo {
  id: FooOperation;
  display: string;
}

export const FooMapping: Foo[] = [...];
like image 164
pzaenger Avatar answered Oct 12 '22 11:10

pzaenger


I had the same problem. The braces have to go after the type:

const FooMapping: [{id: FooOperation, display: string}] 

should be

const FooMapping: {id: FooOperation, display: string}[] 

Easy way to remember this is to replace the object with a type and see if it makes sense:

[string] doesn't work but string[] does

like image 26
PawZaw Avatar answered Oct 12 '22 11:10

PawZaw