首页 > 解决方案 > 打字稿接口允许类型键和字符串值

问题描述

Typescript 中有没有办法动态地使用称为type接口的键?

例如,我有这个type

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

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

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

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

interface person {
  [key: string]: properties
}

像这样的东西:

interface person {
  [key: properties]: string
}

标签: typescript

解决方案


您可以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',
}

推荐阅读