首页 > 解决方案 > 如何在 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 应该显示所有可用的函数。

我们可以使用下面的方法解决这个问题,但问题是每当我们向数学命名空间添加新方法时,它不会建议,直到我们将其添加到 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:

还有没有办法将这种类型转发到反应组件?这样每当我们从道具访问它时,它应该显示列出所有这些功能?

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

标签: typescripttypescript3.0

解决方案


您需要进行returnNewobj泛型以便将目标对象的类型转发到结果:

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

游乐场链接

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


推荐阅读