打字稿中的静态类

时间:2016-03-01 13:37:37

标签: javascript node.js static typescript

有没有办法在typescript,node.js

中创建静态类

我想创建一个静态类来保留所有常量和字符串。

这可能是最好的方法吗?

3 个答案:

答案 0 :(得分:29)

当然,您可以使用静态属性定义类:

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

然后在需要时使用它:

import { Constants } from '../constants';
console.log(Constants.MAX_VALUE);

答案 1 :(得分:7)

您可以将所需的变量和函数放在模块中,这意味着它不必实例化。

module constants {
   export var myValue = 'foo';

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

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

真的没有真正的静态类,但这非常接近复制它。

答案 2 :(得分:1)

现在你可以使用这样的枚举:

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

然后使用它:

import { Numbers } from './Numbers';
Numbers.FIVE