考慮以下組件:
Basic.tsx
type BasicPropertyDetails<T extends unknown> = T & {
label: string
id: string
}
interface Props {
properties: BasicPropertyDetails<unknown>[]
onPropertySelect: <T>(property: BasicPropertyDetails<T>) => void
}
const Basic = ({ properties, onPropertySelect }: Props) => { ... }
Extended.tsx
export interface ExtendedPropertyDetails{
status: string
price: string
}
export interface Props {
ExtraProperties: BasicPropertyDetails<ExtendedPropertyDetails>[]
onPropertySelect: (property: BasicPropertyDetails<ExtendedPropertyDetails>) => void
}
const Extended = ({ ExtraProperties, onPropertySelect }: Props) => {
...
return (
<Basic properties={ExtraProperties} onPropertySelect={onPropertySelect} />
)
}
我需要 onPropertySelect 的 (in Basic.tsx) 型別與傳入的任何型別相同Extended.tsx。即onPropertySelect在 Basic 中應該知道要使用的型別是(property: BasicPropertyDetails<ExtendedPropertyDetails>) => void(基于 中的值Extended.tsx)。
注意:propertyinside的型別onPropertySelect將具有相同的子型別BasicPropertyDetails<unknown>
截至目前,我無法使上述作業正常進行,并且 Extended 中的實作(或回傳 tsx)會因型別不匹配而引發錯誤。
uj5u.com熱心網友回復:
在Extended.tsx中,將型別傳遞T給onPropertySelect屬性。
export interface Props {
ExtraProperties: BasicPropertyDetails<ExtendedPropertyDetails>[]
onPropertySelect: <ExtendedPropertyDetails>(property: BasicPropertyDetails<ExtendedPropertyDetails>) => void
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491825.html
標籤:javascript 节点.js 反应 打字稿
