Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static class in typescript

Is there any way to create an static class in typescript, node.js

I want to create an static class to keep all constants and string in that.

what could be the best way to do that ?

like image 328
Arun Tyagi Avatar asked Mar 01 '16 13:03

Arun Tyagi


People also ask

What is static classes in TypeScript?

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.

Can you create a static class in TypeScript?

The class or constructor cannot be static in TypeScript.

What is the use of static in TypeScript?

Static class means is can not be instantiated, inherited from and also sealed and can not be modified. TypeScript only supports static fields, which simply means you can access those fields without creating an instance of the class.

Does TypeScript have static?

We present Static TypeScript (STS), a subset of TypeScript (itself, a gradually typed superset of JavaScript), and its com- piler/linker toolchain, which is implemented fully in Type- Script and runs in the web browser.


3 Answers

Sure you can define a class with static properties:

export class Constants {
    static MAX_VALUE = 99999;
    static MIN_VALUE = 0;
}

Then use it when you need:

import { Constants } from '../constants';
console.log(Constants.MAX_VALUE);
like image 73
Dmitri Pavlutin Avatar answered Oct 07 '22 01:10

Dmitri Pavlutin


You can put your variables and functions you want inside a module which means that it doesn't have to be instantiated.

module constants {
   export var myValue = 'foo';

   export function thisIsAStaticLikeFunction () {
      console.log('function called');
   }
}

.....
console.log(constants.myValue);

There really is no such thing as a true static class, but this comes pretty close to replicating it.

like image 30
kemiller2002 Avatar answered Oct 07 '22 00:10

kemiller2002


Now you can use Enums like that:

export enum Numbers {
   Four = 4,
   Five = 5,
   Six = 6,
   Seven = 7
}

Then use it:

import { Numbers } from './Numbers';
Numbers.FIVE
like image 26
Josef Kuchař Avatar answered Oct 06 '22 23:10

Josef Kuchař