如何正确地将通用类字段分配给通用本地字段?
例如,我在通用类
中实现了这个通用接口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
类型,但我不想这样做。
答案 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[];
}