【发布时间】:2017-08-21 23:40:08
【问题描述】:
我在 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 类型)。可在打字稿操场上重现:Typescript playground link
【问题讨论】:
标签: typescript