typescript - 打字稿嵌套泛型
问题描述
如何嵌套使用泛型的相同类型?
interface programConfig<T extends Record<string, any>> {
// other types removed; not relevant to the question
commands?: { [key: string]: programConfig<???> }; // how do I type this?
}
更完整的ts 操场示例,显示了我要完成的工作
解决方案
您可以指定第二个泛型来包含 programConfig 的子元素,在此示例中,我限制内部元素不允许第三级嵌套,因为支持任意嵌套会很烦人,希望没有必要
interface BaseProgramConfig<T extends Record<string, unknown> >{
options?: {
[K in keyof T]: {
validator?: () => T[K]
}
},
handler?: (data: T) => void
}
interface programConfigWithCommands<T extends Record<string, unknown>, Sub extends Record<string, Record<string, unknown>>> extends BaseProgramConfig<T> {
commands?: {[K in keyof Sub]: BaseProgramConfig<Sub[K]>}
}
class Program<T extends Record<string, unknown>, Comms extends Record<string, Record<string, unknown>>> {
constructor(config: programConfigWithCommands<T,Comms>) { }
}
const foo = new Program({
options: {
'fruit': { validator: () => 'asdf' },
'animal': { validator: Number },
},
handler: ({ fruit, animal, thing }) => { // fruit and animal are properly typed based on options above
console.log(fruit, animal)
},
commands: {
foo: {
options: {
'tree': { validator: () => 'asdf' },
'person': {},
},
handler: ({ tree, person, thing }) => { // tree is typed as string, person is typed as unknown
console.log(tree, person)
},
}
}
});
推荐阅读
- php - 基于 HTML-PHP-PDO-PostgreSQL 的表单数据插入中整数错误的未定义索引、无效输入语法
- node.js - Google Node.js SDK v2 上的操作:以对象为参数的 conv.ask()
- aws-cli - 在 shell 控制台上监控 AWS Kinesis 流
- sql - 获取两个表之间的数据匹配 - 如果至少三个字符匹配或更多
- spring - Spring Mongo 转换器未注册
- angular - 如何在 Angular 5 应用程序中获取复选框值
- php - 尝试运行 multiqyery 时出错
- c++ - TensorFlow 和 Bazel c++
- javascript - 在 django 中使用 python 函数调用 javascript 函数
- java - 如何使用android中的动画将苹果放入篮子中?