最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript how to assign generics to generic variable field - Stack Overflow

programmeradmin0浏览0评论

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 e.g. 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? It works fine with the type any, but I don't want to do that.

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 e.g. 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? It works fine with the type any, but I don't want to do that.

Share Improve this question edited Feb 17, 2017 at 14:23 Murat Karagöz asked Feb 17, 2017 at 13:22 Murat KaragözMurat Karagöz 37.6k16 gold badges81 silver badges112 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

Your definition of TableBoxProps<T> is wrong. In getDataSource: <T> () => T[];, the <T> shouldn't be here as it declares another generic type T that shadows the TableBoxProps<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 {}. You need to cast it to 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.

发布评论

评论列表(0)

  1. 暂无评论