[英]Using Typescript generics for React Functional Components with eslint props validation
我想使用 Typescript 在 React 中創建一個功能組件,並且我已經根據此 Q&A進行了設置:
export interface CustomProps<T extends object> extends SomeOtherProps<T> {
customProp?: number;
}
const CustomComponent: <T extends object>(props: CustomProps<T>) => JSX.Element = {
customProp = 10,
...props
}) => {
// etc
};
但是,這給了我一個eslint
的錯誤,說這些道具沒有經過驗證:
道具驗證中缺少“customProp”
我可以嘗試通過在默認道具后添加CustomProps
來使用泛型添加道具驗證:
export interface CustomProps<T extends object> extends SomeOtherProps<T> {
customProp?: number;
}
const CustomComponent: <T extends object>(props: CustomProps<T>) => JSX.Element = {
customProp = 10,
...props
}: CustomProps<any>) => {
// etc
};
但這給了我一個“沒有明確any
”的警告。 如果我插入T
,它不會知道。 那么我該如何解決這個問題呢?
解決方案在於再次實例化類型,就像為組件聲明本身實例化它一樣:
export interface CustomProps<T extends object> extends SomeOtherProps<T> {
customProp?: number;
}
const CustomComponent: <T extends object>(props: CustomProps<T>) => JSX.Element = <T extends object>({
customProp = 10,
...props
}: CustomProps<T>) => {
// etc
});
這樣,所有道具都將得到正確驗證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.