打字稿如何将泛型分配给通用变量字段

时间:2017-02-17 13:22:50

标签: javascript generics typescript

如何正确地将通用类字段分配给通用本地字段?

例如,我在通用类

中实现了这个通用接口
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类型,但我不想这样做。

2 个答案:

答案 0 :(得分:2)

这是因为this.props.getDataSource()[row]的类型为{}。你需要把它投到T:

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

您需要使用as T而非<T>,因为您正在使用React和JSX。

答案 1 :(得分:1)

您对TableBoxProps<T>的定义是错误的。在getDataSource: <T> () => T[];中,<T>不应在此处,因为它声明了遮盖T的另一个通用类型TableBoxProps<T>。您实际上是在通用接口中声明了通用函数。

您写的等于:

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

正确的解决方案应该是

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