[英]How do I convert an integer from a Typescript enum to its key value as a type of the union of the keys?
I have two interfaces in Typescript, one of which uses an enum's integer values, and one of which uses the enum's keys: 我在Typescript中有两个接口,其中之一使用枚举的整数值,而其中一个使用枚举的键:
enum foo {
bar = 0,
baz,
}
interface asNumbers {
qux: foo
}
interface asStrings {
quux: keyof typeof foo
}
I would like to take an object implementing asNumbers
and convert it to an object implementing asStrings
. 我想将一个实现
asNumbers
的对象转换为一个实现asStrings
的对象。 I have the following code: 我有以下代码:
const numberObject: asNumbers = {
qux: foo.bar
}
const stringyObject: asStrings = {
quux: foo[numberObject.qux]
}
I receive the following error though on the stringyObject assignment though. 我虽然在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"'.
It is unclear to me how I can take that integer value and convert it into it's key in a typesafe manner (without resorting to more generic string
types). 对我而言,目前尚不清楚如何以类型安全的方式(不求助于更通用的
string
类型)将该整数值转换为键值。 Reproducible on typescript playground: Typescript playground link 在打字稿游乐场可复制: 打字稿游乐场链接
You could define a function that provides some type safety while also meeting your use case: 您可以定义一个在提供某种类型安全性的同时还满足您的用例的函数:
const stringyObject: asStrings = {
quux: getFooProp[numberObject.qux]
}
function getFooProp(i: foo): (keyof typeof foo) {
return foo[i] as (keyof typeof foo);
}
If you wanted to be more generic, then you could define a function like this: 如果您想变得更通用,则可以定义如下函数:
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);
}
The compiler helps us in both cases, and will complain when we pass in an enum value that is not of type foo
. 在这两种情况下,编译器都可以为我们提供帮助,并且当我们传入非
foo
类型的枚举值时会抱怨。
// Works
getEnumProp(foo, foo.bar);
// Argument of type 'foo2.bar'
// is not assignable to parameter of type 'foo'.
getEnumProp(foo, foo2.bar);
Here is a Fiddle for you that demonstrates both. 这是一个小提琴,向您展示了两者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.