How do I nest the same type that uses generics?
interface programConfig<T extends Record<string, any>> {
// other types removed; not relevant to the question
commands?: { [key: string]: programConfig<???> }; // how do I type this?
}
More complete ts playground example that shows what I'm trying to accomplish
CodePudding user response:
You can specify a second generic to encompass the sub elements of the programConfig, in this example I constrained the inner ones to not allow a 3rd level of nesting since supporting arbitrary nesting would be annoying and hopefully not necessary
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)
},
}
}
});
CodePudding user response:
You just need to call new Program
again, like here:
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)
},
})
}
});