如何访问 TypeScript 中的静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16207593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:03:49  来源:igfitidea点击:

How to access static methods in TypeScript

typescript

提问by Kal_Torak

I'm trying to do this, but it's not working like I'd expect.

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

(I'm using the AMD option)

(我正在使用 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

How do you do logger.log()?

你怎么做 logger.log()?

回答by Dimitris

You can import classes directly, which allows you to have the usage you want.

您可以直接导入类,这样您就可以拥有所需的用法。

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

And the definition stays the same.

并且定义保持不变。

// path/logger.ts
export class Logger {

    static Log() {
        ...
    }
}

回答by Jude Fisher

This answer was correct at time of posting. It is now deprecated. See Dimitris' answerfor a better current solution.

这个答案在发布时是正确的。现在已弃用。有关更好的当前解决方案,请参阅Dimitris 的回答

Using a class, you can't. You're always going to have to call {module}.{class}.{function}

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

But you can drop the class altogether and just call {module}.{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