如何在TypeScript中将函数的返回类型指定为名称空间类型,以便提出建议

问题描述

export namespace maths {
    export function add(payload) {
        console.log(payload);
    }
    export function subtract(payload) {
        console.log(payload);
    }    
    export function multiply(payload) {
        console.log(payload);
    }      
}

export const returnNewobj = (obj,name: string) => {
    return Object.assign(obj,{ name });
};

const mathsFunction = returnNewobj(maths,"mathsFunction");
mathsFunction.  // it doesn't suggest the function inside the mathsFunction

我希望mathsFunction应该显示所有可用的函数

我们可以使用以下方法解决此问题,但是问题是,每当我们向maths命名空间添加方法时,建议将其添加到IMaths接口中才建议使用

interface IMaths {
    add: (payload: number) => string;
    substract: (payload: number) => number;
}

const returnNewobj = (actions): IMaths => {
    return actions;
}

const mathsFunction = returnNewobj(maths);
mathsFunction.add(10); // here it shows the suggestion but the issue is we manuly have to sync namespace and type

编辑1:

还有什么方法可以将这种类型转发给react组件?这样当我们从道具访问它时,它应该显示所有这些功能的列表吗?

interface IAppProps {
   actions: any;   // how to forwarded returnNewobj type to this interface?
}

    export class App extends React.Component<AppProps,AppState> {
        constructor(props) {
            super(props);
        }

        fireAction(): void {
            this.props.actions. // should list all those functions which is in namespace
        }
        render() { return () }
    }
    
    const mapdispatchToProps = (dispatch,props) => {
        return { actions: returnNewobj(maths) };
    };
    
    export default connect(null,mapdispatchToProps)(AppComponent);

解决方法

您需要使returnNewobj通用,以便将目标对象的类型转发给结果:

export const returnNewobj = <T,>(obj:T,name: string) => {
    return Object.assign(obj,{ name });
};

Playground Link

注意:不要使用名称空间,现代模块通常是更好的解决方案。