typescript - 打字稿接口允许类型键和字符串值
问题描述
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
为此使用:
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',
}
推荐阅读
- model-view-controller - 是否可以在 Zend Framework 中使用 HTML 表单而不是 ZendForm?
- swift - 使用 Combine 观察泛型值
- firebase - Flutter 依赖冲突将 firebase-admin 添加到我的 pubspec.yaml
- python - 如何在python中更改单选按钮状态?
- laravel-7 - Composer 需要 maatwebsite/excel 未安装
- r - 努力在函数内循环
- java - Spring框架和Jersey集成
- python - 有没有办法在 MobileNetV2 上实现我自己的功能作为预处理?
- python - 如何使用 Python boto3 获取 s3 存储桶中超过 60 天的文件/对象的计数?
- google-app-engine - 如何在没有`dev_appserver.py`的情况下在 2021 年本地运行 App Engine 标准应用程序(用于开发/测试)?