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

如何从T[keyof T]获取精确返回类型?TypeScript类方法优化

问题描述

现有泛型类App<T>,其中T是Record<string, 不同类型>结构的配置对象。想要实现getPart方法,传入T的键名时返回对应键的精确类型(比如传入'part2'就返回Type2)。当前实现的getPart方法返回类型是T[keyof T]联合类型,想知道能不能实现精确返回类型。

现有代码

class App<T> {
    config: T // T 应为 Record<string, 不同类型>
}

// T 的示例配置
const config = {
    'part1': Type1,
    'part2': Type2,
    'part3': Type3
}

期望实现

class App<T> {
    config: T,
    getPart(key) // 根据传入的 T 的键名,返回对应键的精确类型
}

const data = app.getPart('part2') // 期望返回 Type2 类型

尝试过的代码

getPart(key: keyof T): T[keyof T] { // 返回类型变成了 T1 | T2 | T3 联合类型
    return this.config[key];
}
解决方案

可以通过给getPart方法添加泛型参数来实现精确类型返回,让方法的返回类型和传入的键名做绑定:

class App<T> {
    config: T;

    constructor(config: T) {
        this.config = config;
    }

    getPart<K extends keyof T>(key: K): T[K] {
        return this.config[key];
    }
}

// 使用示例
type Type1 = { name: string };
type Type2 = { age: number };
type Type3 = { isActive: boolean };

const app = new App({
    part1: { name: "Alice" } as Type1,
    part2: { age: 25 } as Type2,
    part3: { isActive: true } as Type3
});

const data = app.getPart('part2'); // data 类型为 Type2

原理说明

给getPart方法加个泛型参数K,限定它只能是T的键名。返回类型写成T[K]后,TypeScript就能根据你传入的具体键,精准对应到该键的值类型,不会再返回所有类型的联合了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:36:10