Skip to content
Advertisement

TypeScript static classes

I wanted to move to TypeScript from traditional JS because I like the C#-like syntax. My problem is that I can’t find out how to declare static classes in TypeScript.

In C#, I often use static classes to organize variables and methods, putting them together in a named class, without needing to instatiate an object. In vanilla JS, I used to do this with a simple JS object:

var myStaticClass = {
    property: 10,
    method: function(){}
}

In TypeScript, I would rather go for my C-sharpy approach, but it seems that static classes don’t exist in TS. What is the appropriate solution for this problem ?

Advertisement

Answer

TypeScript is not C#, so you shouldn’t expect the same concepts of C# in TypeScript necessarily. The question is why do you want static classes?

In C# a static class is simply a class that cannot be subclassed and must contain only static methods. C# does not allow one to define functions outside of classes. In TypeScript this is possible, however.

If you’re looking for a way to put your functions/methods in a namespace (i.e. not global), you could consider using TypeScript’s modules, e.g.

module M {
    var s = "hello";
    export function f() {
        return s;
    }
}

So that you can access M.f() externally, but not s, and you cannot extend the module.

See the TypeScript specification for more details.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement