這個問題使用 React 代碼,但特定于 typescript 而不是 react。我正在使用一個簡化的示例來嘗試使其更易于閱讀。我有一個組件MyList,它接受一個傳遞給 props 類型的泛型類型參數(shù)。這種泛型類型推斷出一個用于生成子組件的對象。我想使用T[keyof T]||的值來鍵控每個子組件 它的索引在T[].創(chuàng)建列表并使用索引沒有問題,但我無法弄清楚如何正確鍵入,listKey以便它可以與key預(yù)期的reacts屬性一起使用number | string | undefined。type MyListProps<T> = { list: T[], listKey: keyof T, contentKey: keyof T}class MyList<T extends object> extends React.Component<MyListProps<T>, any> { public render() { return ( <div> { this.props.list.map((value: T, index: number) => { const key = value[this.props.listKey]; return ( // Type T[keyof T] is not assignable // to type 'number | string | undefined' <Item key={key}>{value[this.props.contentKey]}</Item> ); } </div> ); }}我怎么能推斷出該listKey類型可以key使用泛型分配給預(yù)期類型的 reacts道具?
對期望 'number | 的屬性使用泛型類型值。字符串 | 不明確的'
躍然一笑
2021-06-02 17:14:25