[英]How do I convert an integer from a Typescript enum to its key value as a type of the union of the keys?
我在Typescript中有兩個接口,其中之一使用枚舉的整數值,而其中一個使用枚舉的鍵:
enum foo {
bar = 0,
baz,
}
interface asNumbers {
qux: foo
}
interface asStrings {
quux: keyof typeof foo
}
我想將一個實現asNumbers
的對象轉換為一個實現asStrings
的對象。 我有以下代碼:
const numberObject: asNumbers = {
qux: foo.bar
}
const stringyObject: asStrings = {
quux: foo[numberObject.qux]
}
我雖然在stringyObject分配上卻收到以下錯誤。
Type '{ quux: string; }' is not assignable to type 'asStrings'.
Types of property 'quux' are incompatible.
Type 'string' is not assignable to type '"bar" | "baz"'.
對我而言,目前尚不清楚如何以類型安全的方式(不求助於更通用的string
類型)將該整數值轉換為鍵值。 在打字稿游樂場可復制: 打字稿游樂場鏈接
您可以定義一個在提供某種類型安全性的同時還滿足您的用例的函數:
const stringyObject: asStrings = {
quux: getFooProp[numberObject.qux]
}
function getFooProp(i: foo): (keyof typeof foo) {
return foo[i] as (keyof typeof foo);
}
如果您想變得更通用,則可以定義如下函數:
interface NumericEnum {
[id: number]: string
}
function getEnumProp<T extends NumericEnum, K extends keyof T>(
e: T,
i: T[K]): (keyof T) {
return e[i] as (keyof T);
}
在這兩種情況下,編譯器都可以為我們提供幫助,並且當我們傳入非foo
類型的枚舉值時會抱怨。
// Works
getEnumProp(foo, foo.bar);
// Argument of type 'foo2.bar'
// is not assignable to parameter of type 'foo'.
getEnumProp(foo, foo2.bar);
這是一個小提琴,向您展示了兩者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.