如何在 TypeScript 中指定 return 类型的函数作为命名空间类型,以便提出建议

How to specify return type of function as namespace type in TypeScript so that suggestion can come up

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组件吗?这样每当我们从 props 访问它时,它应该显示列出所有这些功能?

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

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