简体   繁体   English

如何在TypeScript中访问静态方法

[英]How to access static methods in TypeScript

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()的?

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() {
        ...
    }
}

This answer was correct at time of posting. 这个答案在发布时是正确的。 It is now deprecated. 它已被弃用。 See Dimitris' answer for 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM