You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript中如何对使用泛型的同类型进行嵌套类型定义

解决方案

你可以根据你的类型推导需求选择以下两种实现方式:

方案1:基础嵌套满足类型约束

如果不需要对各层级command的泛型做精准类型推导,只需要保证类型合法,直接在泛型位传入符合约束的Record<string, any>即可:

interface programConfig<T extends Record<string, any>> {
  // 其他不相关属性省略
  commands?: { [key: string]: programConfig<Record<string, any>> }; 
}

方案2:支持全层级精准类型推导

如果你需要父级配置的泛型可以约束子commands的类型,实现嵌套结构的完整类型提示,可以调整泛型定义,加入子命令的泛型约束:

interface programConfig<
  T extends Record<string, any>,
  Commands extends Record<string, programConfig<any, any>> = Record<string, programConfig<any, any>>
> {
  // 其他基于T的属性定义
  commands?: Commands;
}

// 示例使用
type MyConfig = programConfig<{
  port: number;
  host: string;
}, {
  dev: programConfig<{
    watch: boolean;
    hot: boolean;
  }>,
  build: programConfig<{
    minify: boolean;
    outDir: string;
  }>
}>

内容的提问来源于stack exchange,提问作者user578895

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:24:08