2017-10-20 94 views
0

節點版本: 6.11.3在Typescript中獲取名稱空間的所有值?

打字稿版本: 2.1.6

我們有一羣在我們的項目是枚舉大多是這樣的:

export type ThingType = "thing1" | "thing2"; 

export namespace ThingType { 
    export const THING_ONE = "thing1"; 
    export const THING_TWO = "thing2"; 
} 

我想在終端中爲需要這些字符串值的終端用戶公開這些值。所以我做了一個端點,看起來像這樣:

const enums = { 
    thingType: ThingType, 
    ... 
} 

它返回JSON看起來像:我想這是

"data": { 
    "thingType": { 
     "THING_ONE": "thing1", 
     "THING_TWO": "thing2" 
    } 
} 

輸出,如:

"data": { 
    "thingType": ["thing1", "thing2"] 
} 

對於一個普通的JavaScript對象,這將是相當容易的,我只是在我的端點中添加values()ThingType的末尾。但是在TS中的命名空間或枚舉上不存在values()。我在docs on namespaces in Typescript中沒有找到任何東西,但我覺得有一些東西可以讓我輕鬆獲得枚舉值。

回答

2

命名空間被編譯成純javacsript對象,從而有望Object.values()作品(在支持當然Object.values環境):

export type ThingType = "thing1" | "thing2"; 

export namespace ThingType { 
    export const THING_ONE = "thing1"; 
    export const THING_TWO = "thing2"; 
} 

const enums = { 
    thingType: Object.values(ThingType) 

} 
console.(enums); 

顯示

{ thingType: ['thing1', 'thing2'] } 

如果Object.values不可用它得到稍微詳細些:

const enums = { 
    thingType: Object.keys(ThingType).map(k => ThingType[k]) 

} 
+0

什麼版本TS?我得到一個錯誤,說'值類型ObjectConstructor不存在:/ –

+0

啊,射擊,看起來像它的node7 +,我們現在在節點6上 https://stackoverflow.com/a/40421941/1329321 –

+0

@MikeManfrin - 簡單的解決方法'object.values'不可用:https://stackoverflow.com/questions/38748445/uncaught-typeerror-object-values-is-not-a-function-javascript/38748490#38748490 – tymeJV

相關問題