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 ?
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.
The class or constructor cannot be 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.
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.
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);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With