Home  >  Q&A  >  body text

Using one property in the interface as the array length of another property in the same interface

I have an interface that will be used as props of some components to display different devices. Each device will be placed on a card in a grid column.

This is the interface:

interface EquipmentSectionProps {
  bgColor: "black" | "lightGrey";
  columns: number;
  category: string;
  products: string[];
  productImages: string[];
  productReferals: string[];
}

Given the attribute columns, I want to limit the size of the arrays products, productImages and productReferals by the attribute columns, since their usage is related to the number of columns.

The obvious first attempt is to pass the attribute columns directly into the array, like this:

interface EquipmentSectionProps {
  bgColor: "black" | "lightGrey";
  columns: number;
  category: string;
  products: string[columns];
  productImages: string[columns];
  productReferals: string[columns];
}

However, the response returns:

Cannot find name 'columns'.ts(2304) type columns = /*unresolved*/ any

Is there an easier way to achieve this without creating a duplicate interface and passing properties to the new interface?

P粉032977207P粉032977207421 days ago624

reply all(1)I'll reply

  • P粉194919082

    P粉1949190822023-09-17 12:40:17

    Unfortunately, you cannot limit the length of the array through TypeScript types (such as the interface declaration you showed). You need to write the length check in the component's code.

    Although there is a way to initialize an array with a specific length in javascript, javascript itself has no mechanism to enforce an immutable length. There is nothing to prevent the length of an array from increasing, which means you need to explicitly check the length as needed.

    reply
    0
  • Cancelreply