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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With