【问题标题】:How to access static methods in TypeScript如何在 TypeScript 中访问静态方法
【发布时间】:2013-04-18 22:12:12
【问题描述】:

我正在尝试这样做,但它没有像我预期的那样工作。

(我正在使用 AMD 选项)

//logger.ts
export class Logger {

    static log(message: string) {
        //do stuff
    }
}

//main.ts
import logger = module('services/logger');
logger.log("test"); //The property 'log' does not exist on value of type '"logger"'
logger.Logger.log(); //works

你是怎么做 logger.log() 的?

【问题讨论】:

  • 应该可以正常工作,我有类似的代码工作(也许 TS 版本解决了它)

标签: typescript


【解决方案1】:

此答案在发布时是正确的。现在已弃用。请参阅Dimitris' answer 以获得更好的当前解决方案。

使用类,你不能。你总是要打电话给{module}.{class}.{function}

但是您可以完全放弃课程,只需致电{module}.{function}

// services/logger.ts
export function log(message:string){
 // do stuff
}

//main.ts
import logger = module('services/logger');
logger.log("test"); // Should work

【讨论】:

  • 内部模块对类型系统的贡献方式的变化与这里无关。
  • 我不清楚是否只有内部模块在发生变化。谢谢 - 我会更新。
  • 我一直将它用于实际上是单例的模块。
  • The property 'log' does not exist on value of type "logger"
  • 我更喜欢通过类包装器访问,但我不想必须这样做module.class.function,我希望导入直接别名到类。
【解决方案2】:

你可以直接导入类,让你有你想要的用法。

// usage
import { Logger } from 'path/logger.ts'
Logger.Log();

定义保持不变。

// path/logger.ts
export class Logger {

    static Log() {
        ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2023-03-07
    相关资源
    最近更新 更多