Is it possible to specify the length of the array that comes from props using type from Typescript?
We have an array of objects:
const arrayPassedViaProps = [
{ key: '1', label: 'Label 1', value: 9 },
{ key: '2', label: 'Label 2', value: 3 },
{ key: '3', label: 'Label 3', value: 3 },
{ key: '4', label: 'Label 4', value: 22 },
{ key: '5', label: 'Label 5', value: 1 }
]
I pass this array as props like this:
<DownlineProgress data={arrayPassedViaProps} />
Inside DownlineProgress component I defined a type:
type DownlineProgressBarProps = {
data: {
key: string
label: string
value: number
}[]
}
I'm using this type with props
export const DownlineProgress = ({data}: DownlineProgressBarProps) => ...
I would like to be informed by Typescript when I'm passing props that the array doesn't have the correct length, it should contain TWO or THREE objects
How I can modify my type to achieve such behavior?
PS. currently I'm using if statement to check
if(data.length > 3 || data.length < 2){
throw(`DownlineProgress need an array of length 2 or 3. You pass ${data.length}`)
}