首页 > 解决方案 > 使用多个泛型参数扩展 TypeScript 类

问题描述

我尝试使用通用参数扩展 React 组件类,但我无法让它工作。根据 TypeScript Docs 和这个TypeScript Class Generic Parameter Constraints,以及使用通用 T 扩展一个类,我最终得到以下(不工作)代码:

基类:

class BaseView<P, S> extends React.Component<P, S> {
    public constructor(props: P, state: S) {
        super(props, state);
    }
}

const mapStateToProps = store => {
    console.log('store', store);
    return {
        store
    };
};

function mapDispatchToProps(dispatch) {
    console.log('dispatch', dispatch);
    return {
    };
}

export default connect(mapStateToProps, mapDispatchToProps)((BaseView as any));

export function subclass<P, S>(c): BaseView<P, S> {
    return c;
}

扩展基类的类

我尝试了不同的方法,使用这样的工厂:

export class Documents extends subclass(BaseView)<DocumentsProperties, DocumentsState> { 
// this leads into ""BaseView<{}, {}>" is no constructor function type

或不使用工厂:

export class Documents extends BaseView<DocumentsProperties, DocumentsState> { 
// no base constructor has the specified number of type arguments

我还尝试了其他几种方法,但我觉得这是我人生中的第一次编程......我无法让它运行多个参数。我在这里想念什么?

问候梅瑟比尔

标签: javascripttypescriptreact-reduxtypescript-generics

解决方案


推荐阅读