5

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 2

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[];
}
Sign up to request clarification or add additional context in comments.

2 Comments

is this expression export interface TableBoxProps<T1> { getDataSource<T2>: () => T2[]; } equal to this expression? export interface TableBoxProps<T1> { getDataSource: <T2> () => T2[]; }
@ArelSapir nope, the first one is not even valid code. Interface members cannot be generic, they may only contain a generic function.
1

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.

8 Comments

Thx. Since I am using ReactJs I had to cast it with this.props.getDataSource()[row] as T.
But can you explain why I have to cast it to T when I am in the generic class anyways?
Please show your class definition - it may be in there
This is actually only a workaround that hides the actual problem which I've described in stackoverflow.com/a/57400076/1660584 .
but, if T is defined in a class it would be. nevermind
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.