簡體   English   中英

打字稿如何將泛型分配給泛型變量字段

[英]Typescript how to assign generics to generic variable field

如何將通用類字段正確分配給通用本地字段?

例如,我在通用類中實現了這個通用接口

export interface TableBoxProps<T> {
   getDataSource: <T> () => T[];
}

class Container<T> extends React.Component<TableBoxProps<T>, any>{ ... }

在某處我有一個函數,我想從數據源中獲取一個條目,例如像這樣

 private onCellClick = (row: number, column: number) => {
      let entity:T = this.props.getDataSource()[row]; // error
   }

我收到上述錯誤

[ts] Type '{}' is not assignable to type 'T'

我必須改變什么才能使用let entity:T 它適用於any類型,但我不想這樣做。

您對TableBoxProps<T>定義是錯誤的。 getDataSource: <T> () => T[]; <T>不應該在這里,因為它聲明了另一個TableBoxProps<T>泛型類型T 您實際上在泛型接口中聲明了泛型函數。

您所寫的內容等於:

export interface TableBoxProps<T1> {
   getDataSource: <T2> () => T2[];
}

正確的解決方案應該是

export interface TableBoxProps<T> {
   getDataSource: () => T[];
}

這是因為this.props.getDataSource()[row]的類型是{} 您需要將其轉換為 T:

let entity: T = (this.props.getDataSource()[row] as T);

您需要使用as T而不是<T>因為您使用的是帶有 JSX 的 React。

暫無
暫無

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

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