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 arraysproducts
,productImages
andproductReferals
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?
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 away 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.