如何嵌套使用泛型的相同型別?
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 playground示例,顯示了我正在嘗試完成的作業
uj5u.com熱心網友回復:
您可以指定第二個泛型來包含 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)
},
}
}
});
uj5u.com熱心網友回復:
你只需要new Program再次呼叫,就像這里:
type programConfig<T extends Record<string, any> = Record<string, any>> = {
options?: {
[K in keyof T]: {
validator?: () => T[K]
}
},
handler?: (data: T) => void,
commands?: { [key: string]: Program<Record<string,unknown>> }; // here use sub-programs that have nothing to do with T
}
class Program<T extends Record<string, any> = Record<string, any>> {
constructor(config: programConfig<T>) { }
}
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: new Program({
options: {
'tree': { validator: () => 'asdf' },
'person': {},
},
handler: ({ tree, person, thing }) => { // tree and person are typed in the same way and Program of any type is accepted in commands
console.log(tree, person)
},
})
}
});
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363830.html
