Reputation: 85
I'm new to Typescript thought I got a hang of it but ran into an issue today of creating an interface for a complex dynamic object from JSON, converted it to generic names for the attributes below.
I'm getting error messages "Source has X element(s) but target allows only 1.". How can I extend my arrays to accept multiple objects, but still retain the attribute names? I have seen indexer solutions but it seems to loose the value of getting an expected JSON object overview.
interface Props {
arrayName: [
{
attributeName: string;
attributeArray: [
{
attributeToken: string;
attributeArray: [
{
attributeName: number;
attributeName: number;
comment: string;
},
];
},
];
attributeArray: [
{
attrbuteName: string;
attributeValue?: number;
attributeLevel: number | null;
attributeMeasurement: number | null;
attributeUnit?: string;
},
];
attributeBoolean: false;
attributeValue: 199.0;
}
];
}
Upvotes: 1
Views: 557
Reputation: 187232
The type [SomeType]
is a tuple with one element. To declare an array with an unknown number of items use SomeType[]
The tuple form lets you make a type like [number, string, boolean]
which requires a number at index zero, a string at index 1, and a boolean at index 2. There must be exactly 3 items in the array, and the type of each index is known at compile time.
So you don't want a tuple here. Fixing it is simple. Instead of:
attributeArray: [
{
attributeName: number;
attributeName: number;
comment: string;
},
];
You want:
attributeArray: {
attributeName: number;
attributeName: number;
comment: string;
}[],
Upvotes: 1