How to access static methods in TypeScript

Typescript

Typescript Problem Overview


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

(I'm using the AMD option)

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

Typescript Solutions


Solution 1 - Typescript

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

Solution 2 - Typescript

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

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

But you can drop the class altogether and just call {module}.{function}:

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKal_TorakView Question on Stackoverflow
Solution 1 - TypescriptDimitrisView Answer on Stackoverflow
Solution 2 - TypescriptJude FisherView Answer on Stackoverflow