Typescript如何将泛型分配给泛型变量字段

Mur*_*göz 5 javascript generics typescript

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

例如,我在通用类中实现了这个通用接口

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

class Container<T> extends React.Component<TableBoxProps<T>, any>{ ... }
Run Code Online (Sandbox Code Playgroud)

在某个地方我有一个函数,我想从数据源获取条目,例如像这样

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

我收到上述错误

[ts] Type '{}' is not assignable to type 'T'
Run Code Online (Sandbox Code Playgroud)

我需要改变什么才能使用let entity:T?它与 type 配合得很好any,但我不想这样做。

Jam*_*ger 1

这是因为this.props.getDataSource()[row]is 类型引起的{}。您需要将其投射到 T:

let entity: T = (this.props.getDataSource()[row] as T);
Run Code Online (Sandbox Code Playgroud)

您需要使用as T而不是<T>因为您正在将 React 与 JSX 结合使用。