繁体   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