打字稿:使用嵌入对象作为常量

时间:2016-03-29 15:56:37

标签: typescript

在JavaScript中我使用这样的常量:

module.exports = {
    ACTIONS: {
        ACTION1: "Action",
        ACTION2: ...
    }
    TEST: "test",
    ...
};

接下来就像这样使用它:

var Constants = requre(../utils/constants.js);
console.log(Constants.ACTIONS.ACTION1); //Action
console,log(Constants.TEST); //test

有没有办法在Typescript中使用类似的结构?

3 个答案:

答案 0 :(得分:1)

你可以这样做,使用方法get,这将保持属性只读:

module Constants {
    export class Actions {
        public static get ACTION1(): string { return "ACTION1"; }
        public static get ACTION2(): string { return "ACTION2"; }
    }

    export class Test {
        public static get TEST1(): string { return "TEST1"; }
        public static get TEST2(): string { return "TEST2"; }
    }
}

然后打电话如下:

console.log(Actions.ACTION1); //Action
console.log(Test.TEST1); //Test

答案 1 :(得分:0)

你可以在TypeScript中做同样的事情:

// utils/constants.ts
export = {
    ACTIONS: {
        ACTION1: "Action"
    },
    TEST: "test"
};

然后在你的另一个文件中:

import Constants = require("./../utils/constants");

console.log(Constants.ACTIONS.ACTION1); // Action
console.log(Constants.TEST);            // test

ES6进口

如果您正在使用ES6导入,则可以执行以下操作:

export default {
    ACTIONS: {
        ACTION1: "Action"
    },
    TEST: "test"
};

然后:

import Constants from "./../utils/constants";
// use Constants here

答案 2 :(得分:-2)

也许就像。

module Constants{
    export enum Actions {
        ACTION1 = <any> 'Action1'

    }

    export enum Test {
        TEST1 = <any> 'Test1'

    }

    export const TEST = 'TEST';

}

class HelloWorld{
    public static main(){

        console.log(Constants.Actions.ACTION1);
        console.log(Constants.Test.TEST1);

        console.log(Constants.TEST);
    }
}
HelloWorld.main();

控制台:

Action1
Test1
TEST