Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access static methods in TypeScript

Tags:

typescript

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

like image 752
Kal_Torak Avatar asked Apr 25 '13 06:04

Kal_Torak


People also ask

How do you call a static method in TypeScript?

A static method uses the static keyword instead of the function keyword when we define it. Static members can be encapsulated with the public, private and protected modifiers. We call a static method directly on the class, using the class name and dot notation. We don't need to create an object instance.

What does static do in TypeScript?

Static class means is can not be instantiated, inherited from and also sealed and can not be modified. Static class in TypeScript is not natively supported but you can fake it: function Protect(target: any): void { Object. freeze(target); Object.

Does TypeScript support static classes?

The class or constructor cannot be static in TypeScript.


2 Answers

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() {
        ...
    }
}
like image 188
Dimitris Avatar answered Oct 11 '22 19:10

Dimitris


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
like image 13
Jude Fisher Avatar answered Oct 11 '22 18:10

Jude Fisher