typescript - 打字稿:如何在类型参数中定义一组可能的键?
问题描述
我的计划是:
enum hobbies {
music = 'music',
sports = 'sports'
}
type Hobbies <T extends Array<keyof typeof hobbies>> = {
[key in T]: number
}
type Musician = {
hobbies: Hobbies<["music"]>
}
type Racer = {
hobbies: Hobbies<["racing"]> //errors, fine
}
const musician: Musician = {
hobbies: {
music: 2,
racing: 1 //should error but it doesn't
}
}
问题是它实际上确实抛出了一个错误,但它确实key in T
和它无效一样。
所以如果我用 hobbies.racing 定义 Musician 就不会出错
有什么解决方案吗?
解决方案
没有严格回答问题,但您可以使用联合类型而不是数组:
enum hobbies {
music = 'music',
sports = 'sports'
}
type Hobbies <T extends keyof typeof hobbies> = {
[key in T]: number
}
type Musician = {
hobbies: Hobbies<"music">
}
type Racer = {
hobbies: Hobbies<"racing"> //errors, fine
}
const musician: Musician = {
hobbies: {
music: 2,
racing: 1 //now errors
}
}
要指定多个允许的键,只需使用联合类型:
hobbies: Hobbies<"music" | "sports">
要回答原始问题并使阵列工作:
type Hobbies <T extends Array<keyof typeof hobbies>> = {
[key in T[number]]: number
}
注意key in T[number]
- 键在数组值上
推荐阅读
- r - R ggplot 文本变量在标题中使用两个日期变量
- r - ggplot,根据采样时间的数据空间?
- python - 使用 tkinter 时,如何保存变量以供将来使用?
- amazon-web-services - 如何使用 aws-cdk python 设置 API 密钥
- laravel - 扩展和自定义 Laravel 重置密码逻辑
- python-3.x - 从 pdpbox 导入 pdp、get_dataset、info_plots 时出现 Python 错误
- sas - Proc sql如何使用生日提取大于18yrs的成员记录
- python - 从文件路径中提取“时间”
- javascript - 在字符串中格式化日期
- python - 如何将具有相等相邻条目的数组中的所有条目“归零”?