1

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;
    }
  ];
}

1 Answer 1

1

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;
      }[],
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.