【问题标题】:Typescript interface allowing key of type, and string valuesTypescript 接口允许类型键和字符串值
【发布时间】:2020-11-04 09:49:21
【问题描述】:

Typescript 中有没有办法动态地使用已知的type 作为界面的键?

例如,我有这个type

type properties = 'name' | 'age' | 'height';

我想允许一个对象使用任何/所有这些“属性”作为键,并使用一个字符串作为值:

{name: 'abc', height: '2'}{height: '2'} 允许

我已经使用值而不是键来完成此操作,所以我想要与此相反:

interface person {
  [key: string]: properties
}

类似这样的:

interface person {
  [key: properties]: string
}

【问题讨论】:

  • type person = { [key in properties]?: string }

标签: typescript


【解决方案1】:

您可以为此使用type

type Properties = 'name' | 'age' | 'height';
type Person = {
    [key in Properties]: string
}

// This is allowed
const allowed: Person = {
    name: 'the-name',
    age: '21',
    height: '180',
}

// This has error
const errored: Person = {
    name: 'the-name',
    age: '21',
    height: '180',
    anotherKey: 'foo',
}

【讨论】:

  • 谢谢!我添加了?: string 以满足可选情况。
猜你喜欢
  • 2017-05-07
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 1970-01-01
  • 2021-12-25
  • 2018-09-08
相关资源
最近更新 更多