【问题标题】:Typescript can't access exported method from another moduleTypescript 无法访问从另一个模块导出的方法
【发布时间】:2015-12-27 01:07:01
【问题描述】:

无法引用和使用来自另一个模块的导出方法。收到一条错误消息,指出“SecondModule 中没有导出的成员”。

module FirstModule{
    export class someClass{
         constructor(method: SecondModule.exMethod)   //Getting Error here: 'There is no exported member in SecondModule'
         {}
    }
}

module SecondModule{
    export function exMethod(){
        return function(input){
             //do something
             return result;
        }
    }

}

【问题讨论】:

    标签: angularjs visual-studio typescript


    【解决方案1】:

    您不能将函数引用用作类型;但是,您可以将构造函数限制为特定的函数类型,该类型允许具有 exMethod 等签名的函数。

    这是一个例子:

    module FirstModule {
        export class someClass {
             constructor(method: () => (input) => any) {
             }
        }
    }
    
    module SecondModule {
        export function exMethod() {
            return function(input) {
                 // do something
                 return result;
            }
        }
    }
    
    new FirstModule.someClass(SecondModule.exMethod); // ok
    new FirstModule.someClass(() => {});              // error
    

    如果你想强制 SecondModule.exMethod 被传入,你不妨跳过它,直接在 someClass 中调用函数:

    module FirstModule {
        export class someClass {
             constructor() {
                 SecondModule.exMethod()(5); // example of calling it
             }
        }
    }
    

    【讨论】:

    • 如果不通过构造函数直接在FirstModule中调用函数为SecondModule.exMethod(input)会怎样?
    • @syamalparikh 所以你希望这两个语句是等价的? SecondModule.exMethod()(4);SecondModule.exMethod(4);
    • 对不起,如果我直接从 FirstModule 调用 SecondModule.exMethod()(4) 会怎样?会不会有初始化问题?
    • @syamalparikh 我刚刚将答案更新为不会将FirstModuleSecondModule 混合在一起并将它们分开的东西。如果你愿意的话,你可以从第一个模块中调用SecondModule.exMethod()(4)
    • 在更新后的代码中,FirstModule 标识 'exMethod' 将如何仅通过参数和返回类型?如果 SecondModule 的方法具有相似的返回类型和参数会怎样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2020-07-16
    • 1970-01-01
    相关资源
    最近更新 更多