mmoron mmoron - 1 month ago 10
React JSX Question

how to strongly type react component in typescript?

I'm trying to create strongly typed base class for react

Component
including
RouteComponentProps
. What I'd like to achieve is something like this:

import * as React from "react";

interface IDetailsModel {
show: string;
}

interface IComponentProps<TParams, TProps> extends ReactRouter.RouteComponentProps<TParams, {}>, TProps {
}

class ComponentBase<TParams, TProps> extends React.Component<IComponentProps<TParams, TProps>, {}> {

}

class Details extends ComponentBase<{ id: number }, { show: string; }> {
render() {
var show = this.props.show;
var id = this.props.params.id;
return (
<div className="container"></div>
);
}
}


This is not working, because I
IComponentProps
can't extend
TProps
in a way I wanted it to.

When I substitute TProps with concrete interface in IComponentProps definition like this, everything works:

interface IComponentProps<TParams, TProps> extends ReactRouter.RouteComponentProps<TParams, {}>, IDetailsModel{
}


Is there any other way to achieve this?

Answer

I'm pretty sure that an intersection type should do it:

interface IComponentProps<TParams> extends ReactRouter.RouteComponentProps<TParams, {}> {}

class ComponentBase<TParams, TProps> extends React.Component<IComponentProps<TParams> & TProps, {}> {}

class Details extends ComponentBase<{ id: number }, { show: string; }> {
    render() {
        var show = this.props.show;
        var id = this.props.params.id;
        return (
            <div className="container"></div>
        );
    }
}