简体   繁体   English

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

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

How do I correctly assign a generic class field to a generic local field?如何将通用类字段正确分配给通用本地字段?

For example I have this generic interface implemented in a generic class例如,我在通用类中实现了这个通用接口

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

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

and somewhere I have a function where I want to get an entry from the datasource eg like this在某处我有一个函数,我想从数据源中获取一个条目,例如像这样

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

I get the error with the above我收到上述错误

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

What do I have to change that I can use let entity:T ?我必须改变什么才能使用let entity:T It works fine with the type any , but I don't want to do that.它适用于any类型,但我不想这样做。

Your definition of TableBoxProps<T> is wrong.您对TableBoxProps<T>定义是错误的。 In getDataSource: <T> () => T[];getDataSource: <T> () => T[]; , the <T> shouldn't be here as it declares another generic type T that shadows the TableBoxProps<T> . <T>不应该在这里,因为它声明了另一个TableBoxProps<T>泛型类型T You actually declared a generic function in a generic interface.您实际上在泛型接口中声明了泛型函数。

What you have written is equal to:您所写的内容等于:

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

And correct solution should be正确的解决方案应该是

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

This is caused because this.props.getDataSource()[row] is of type {} .这是因为this.props.getDataSource()[row]的类型是{} You need to cast it to T:您需要将其转换为 T:

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

You need to use as T rather than <T> because you are using React with JSX.您需要使用as T而不是<T>因为您使用的是带有 JSX 的 React。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM