Inferred Generic Type on React Component

a 夏天 提交于 2019-12-10 11:09:53

问题


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?


回答1:


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); }} />;


来源:https://stackoverflow.com/questions/40895388/inferred-generic-type-on-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!