簡體   English   中英

TypeScript 從參數推斷通用 class

[英]TypeScript infer generic class from argument

我有一個通用的 class:

type ItemTemplateProps<T> = { children: (item:T, index:number) => ReactElement, onPress?: (item:T) => void, itemKey?:string }
export default class ItemTemplate<T> extends Component<ItemTemplateProps<T>>{

}

我正在嘗試在 JSX 中使用它( ContentGridCell在這種情況下采用名為Content的道具content ,並且傳遞給onPressc也是同一類):

<ItemTemplate onPress={c => this.presentContent(c.id)}>
{
    item => <ContentGridCell content={item}/>
}
</ItemTemplate>

然而,TypeScript 並沒有推斷出 function 中的類型:

在此處輸入圖像描述

它抱怨參數c unknown

當我明確指定我的 class 時,一切正常:

<ItemTemplate<Content> onPress={c => this.presentContent(c.id)}>
{
    item => <ContentGridCell content={item}/>
}
</ItemTemplate>

但我不想明確指定<Content> 我希望推斷出這種類型。 我不明白為什么當我明確地將它與類型一起使用時它不會自動推斷出來。 我該怎么做? (我在 TypeScript 3.7.2 上)

您是否嘗試過讓其他參數(索引)成為可選的簡單方法?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM