admin管理员组文章数量:1326293
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.
2 Answers
Reset to default 2Your 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.
本文标签: javascriptTypescript how to assign generics to generic variable fieldStack Overflow
版权声明:本文标题:javascript - Typescript how to assign generics to generic variable field - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742208939a2433342.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论