如何强力键入打字稿中的反应成分?

时间:2016-10-26 17:42:18

标签: reactjs typescript

我尝试为包含Component的反应RouteComponentProps创建强类型基类。我想要实现的是这样的:

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

这不起作用,因为我IComponentProps无法以我想要的方式扩展TProps

当我在IComponentProps定义中用具体接口替换TProps时,一切正常:

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

还有其他方法可以达到这个目的吗?

1 个答案:

答案 0 :(得分:1)

我很确定intersection type应该这样做:

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