Using one property in the interface as the array length of another property in the same interface
P粉032977207
P粉032977207 2023-09-16 23:36:08
0
1
401

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粉032977207
P粉032977207

reply all(1)
P粉194919082

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!