首页 > 解决方案 > 打字稿嵌套泛型

问题描述

如何嵌套使用泛型的相同类型?

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 操场示例,显示了我要完成的工作

标签: typescriptgenericstypescript-generics

解决方案


您可以指定第二个泛型来包含 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)
      },
    }
  }
});


推荐阅读