typescript 打字稿中的静态类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35724420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Static class in typescript
提问by Arun Tyagi
Is there any way to create an static class in typescript, node.js
有没有办法在 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 ?
什么是最好的方法呢?
回答by Dmitri Pavlutin
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);
回答by kemiller2002
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.
真的没有真正的静态类这样的东西,但这非常接近复制它。
回答by Josef Kucha?
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