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

TypeScript实现依赖彼此的泛型类型时遇阻求助

问题:合并配置获取函数的TypeScript类型错误解决

我有两种配置类型:auth配置和不含敏感变量的通用配置。原本使用两个函数处理,现在想要合并为一个函数,但代码出现类型错误,无法找到问题所在。不想用//@ts-ignore忽略错误,求可行解决思路。

原代码如下:

interface config {
    config: string;
    config_example: string;
} 

interface auth {
    auth: string;
    auth_example: string;
}

type configType = "auth" | "config";
type getType<C extends configType> = C extends "auth" ? keyof auth : C extends "config" ? keyof config : never;

const auth: auth = {
    auth: '',
    auth_example: ''
}

const config: config = {
    config: '',
    config_example: ''
}

function getConfig<
    C extends configType,
    K extends keyof getType<C>
>(config: C, key: K): getType<C>[K] {
    switch (config) {
        case "auth":
            return auth[key];
        case "config":
            return config[key];
        default:
            throw new Error();
    }
} 

解决思路

问题核心是TypeScript无法在switch分支中正确缩小泛型类型C的范围,导致返回值类型无法匹配预期。可以通过配置映射对象重构代码,让TypeScript能直接推断出类型关联:

重构后的代码

// 接口名改用大驼峰,避免和变量名冲突
interface Config {
    config: string;
    config_example: string;
} 

interface Auth {
    auth: string;
    auth_example: string;
}

type ConfigType = "auth" | "config";

// 创建类型映射,明确关联配置类型与对应接口
type ConfigMap = {
    auth: Auth;
    config: Config;
};

// 统一存储配置实例
const configStore: ConfigMap = {
    auth: {
        auth: '',
        auth_example: ''
    },
    config: {
        config: '',
        config_example: ''
    }
};

function getConfig<C extends ConfigType, K extends keyof ConfigMap[C]>(
    configType: C, 
    key: K
): ConfigMap[C][K] {
    // 通过索引访问直接获取对应配置,类型自动匹配
    return configStore[configType][key];
}

关键改进点

  1. 统一配置存储:用configStore对象关联配置类型字符串和对应的配置实例,让TypeScript能通过索引访问推断出准确类型。
  2. 类型映射简化:用ConfigMap直接关联ConfigType和对应的接口类型,替代原有的条件类型getType,逻辑更清晰。
  3. 命名规范修正:接口名改用大驼峰(Config/Auth),避免和变量名冲突,提升代码可读性。

这样重构后,函数的类型推断完全正确,不需要任何类型断言或忽略错误,同时代码结构更简洁易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:55:21