是否可以使用typeTypescript指定來自 props 的陣列的長度?
我們有一個物件陣列:
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 }]
我將此陣列作為道具傳遞,如下所示:
<DownlineProgress data={arrayPassedViaProps} />
在 DownlineProgress 組件中,我定義了一個型別:
type DownlineProgressBarProps = {
data: {
key: string
label: string
value: number
}[]
}
我正在使用這種型別的道具
export const DownlineProgress = ({data}: DownlineProgressBarProps) => ...
當我傳遞道具時,我希望 Typescript 通知我陣列的長度不正確,它應該包含兩個或三個物件
我如何修改我的type以實作這種行為?
附注。目前我正在使用if陳述句來檢查
if(data.length > 3 || data.length < 2){
throw(`DownlineProgress need an array of length 2 or 3. You pass ${data.length}`)
}
uj5u.com熱心網友回復:
這是一個純 TypeScript 解決方案:
interface Data {
key: string;
label: string;
value: number;
}
// The following type should have two or three elements of type Data
type ArrayWithTwoOrThreeDataElements = [ Data, Data, Data? ];
在您的情況下,由于在 props 值中您期望具有名為dataData 型別的屬性的物件,您可以按如下方式定義 props 的型別:
type DownlineProgressBarProps = [
{ data: Data },
{ data: Data },
{ data: Data }?
];
當然,如果您想避免重復資料屬性鍵,您可以為單個道具專案創建一個型別:
interface Data {
key: string;
label: string;
value: number;
}
interface DownlineProgressBarProp {
data: Data
}
type DownlineProgressBarProps = [
DownlineProgressBarProp,
DownlineProgressBarProp,
DownlineProgressBarProp?
];
uj5u.com熱心網友回復:
您可以使用以下自定義型別指定陣列的長度:
type TupleOf<T, N extends number> = N extends N ? number extends N ? T[] : _TupleOf<T, N, []> : never;
type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N ? R : _TupleOf<T, N, [T, ...R]>;
進而:
type DownlineProgressBarProps = {
data: TupleOf<{
key: string
label: string
value: number
}, 2 | 3>
}
uj5u.com熱心網友回復:
您可以創建一個自定義函式,這將是正確的方法。
const propTypes = {
data: arrayOfLength.bind(null, 2)
}
const arrayOfLength = (expectedLength, props, propName, componentName) => {
const arrayPropLength = props[propName].length
if (arrayPropLength !== expectedLength) {
return new Error(
`Invalid array length ${arrayPropLength} (expected ${expectedLength}) for prop ${propName} supplied to ${componentName}. Validation failed.`
)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/337014.html
標籤:javascript 反应 打字稿
上一篇:在React中使用SCSS@exportedclassNames的更短方法(Next.js css-modules)
