Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 400
Murat Karagöz Avatar asked Oct 18 '22 17:10

Murat Karagöz


2 Answers

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[];
}
like image 70
amik Avatar answered Nov 04 '22 20:11

amik


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.

like image 32
James Monger Avatar answered Nov 04 '22 19:11

James Monger