2016-06-09 107 views
0

我正在寫一個函數來獲取枚舉的字符串值。Typeof泛型導致錯誤

const getEnumValueToString = <T>(enumValue: T, _enum: typeof T): string => _enum[enumValue] 

不過,我得到一個錯誤:Cannot find name T

我看到https://github.com/Microsoft/TypeScript/issues/204但枚舉沒有構造函數所以這是行不通的。我知道我可以直接插入它或使用any但我想知道如何正確鍵入此功能。

回答

1

功能:

<T>(enumValue: T, _enum: typeof T): string => _enum[enumValue] 

是相當無用的。這是因爲它更容易做SomeEnum[SomeEnum.Member]而不是調用這個函數。 TypeScript已經理解枚舉的數字訪問導致字符串例如:

enum Color { 
    Red 
} 

let foo = Color[Color.Red]; // foo is inferred to be a string 
+0

我明白這一點。我仍然想知道如何輸入函數。 – 2426021684

+2

你不需要通用的例如'const getEnumValueToString =(enumValue:number,_enum:{[key:number]:string}):string => _enum [enumValue]' – basarat

+1

謝謝。我不能相信我錯過了這一點。 – 2426021684