Sandy Gifford Sandy Gifford - 8 days ago 4
React JSX Question

Inferred Generic Type on React Component

Typescript is pretty good about inferred generic types. For example, if I write the following code:

class AwesomeClass<T> {
constructor(public val: T) {
// ...
}

public getVal(): T {
return this.val;
}
}

const inst = new AwesomeClass("Hello World");
const result = inst.getVal();


result
is automatically typed to
string
. Nifty! I'd like to take that a step further with React.

If I make the follow component

interface IProps<T> {
value: T;
onClick: (result: T) => void;
}
interface IState { }

class AwesomeComponent<T> extends React.Component<IProps<T>, IState> {
// ...
}


I'd really like it to be inferred that
value
has to have the same type as the
result
argument of
onClick
. Instead when I initialize the component with

<AwesomeComponent
value="Hello World"
onClick={(v) => { console.log(v); }} />;


I get a compile error
error TS2322: Type 'string' is not assignable to type 'T'
.

Is it possible to infer the generic type on a React element's props?

I realize that the JSX transpiles to a call to
React.createElement
(it doesn't directly initialize the class like I do with my
AwesomeClass
example above) and that this may complicate the process - is that a deal killer? If so, can I explicitly name a generic type using the JSX syntax?

Answer

This isn't possible yet, here's an issue about it: Using lookahead to detect generic JSX elements?.

For now what you'll need to do is:

interface IProps<T> {
    value: T;
    onClick: (result: T) => void;
}
interface IState { }

class AwesomeComponent<T> extends React.Component<IProps<T>, IState> {
    // ...
}

class ConcreteAwesomeComponent extends AwesomeComponent<string> {}

<ConcreteAwesomeComponent
    value="Hello World"
    onClick={(v) => { console.log(v); }} />;