繁体   English   中英

typescript:在包含空格的接口中使用枚举值作为键

[英]typescript: Use enum value as key in interface containing spaces

我有一个枚举,我想将它的添加到一个接口,但得到这个错误:

接口中的计算属性名称必须引用其类型为文字类型或“唯一符号”类型的表达式。(1169)

https://www.typescriptlang.org/play?ts=4.5.2#code/KYOwrgtgBAYglsANgEwM5QN4CgpQOQgCGEweUAvPgGYIoCMeANDvoQOakW541LIBMTFngDGYVABcA9tF4oylHrWQBmIQF8sWOCAnAATlUIjgUAAoHUUkJhZxkALiiT9OtgG4WAbXh9UX0XFpWWU8AF0wgH4nFzdPdSA

如何使用枚举值作为接口属性,而不必使用反向键/值创建第二个枚举?

enum Fields {
  'name' = 'field1',
  'age' =  'field2',
  'custom field' = 'field3',
}

interface Person {
  id: string;
  [Fields['custom field']]?: string;
}

我认为您可以使用中间类型来实现您想要的,如下所示:

enum Fields {
  'name' = 'field1',
  'age' =  'field2',
  'custom field' = 'field3',
}

type FieldsObject = {
    [K in Fields]? : string
}

interface Person extends FieldsObject {
  id: string;
}

const p: Person = {
  id: "abc",
  field1: "",
  field3: "",
}

TypeScript 游乐场展示了这个

我有一个解决方案,但它很丑:基本上,使用映射类型来定义该属性,然后与常规 object 类型相交以定义属性的 rest。 我使用Simplify使结果更具可读性。

type Simplify<T> = T extends unknown ? {[K in keyof T]: T[K]} : never

type Person = Simplify<{
  id: string;
} & {
  [K in typeof Fields['custom field']]?: string
}>

将鼠标悬停在 Typescript Playground 中的Person上显示结果相当于:

type Person = {
    id: string;
    field3?: string | undefined;
}

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM