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

TypeScript缓存类中如何让get方法正确推断set的返回类型?

解决TypeScript缓存类的返回类型推断问题

你的问题在于当前Cache类使用了any类型,导致TypeScript无法跟踪每个缓存键对应的值类型。要实现get方法自动推断set时传入的resolve函数返回类型,需要让类在类型层面记录每个键的类型信息。

修改后的实现代码

type StoreEntry<T> = {
    current: T;
    resolve: () => T;
};

class Cache<KeyMap extends Record<PropertyKey, unknown> = {}> {
    private store = new Map<PropertyKey, StoreEntry<unknown>>();

    set<K extends PropertyKey, V>(key: K, resolve: () => V): Cache<KeyMap & Record<K, V>> {
        this.store.set(key, {
            current: resolve(),
            resolve
        });
        return this as Cache<KeyMap & Record<K, V>>;
    }

    get<K extends keyof KeyMap>(key: K): KeyMap[K] | undefined {
        const entry = this.store.get(key) as StoreEntry<KeyMap[K]> | undefined;
        return entry?.current;
    }
}

使用示例

const cache = new Cache()
    .set("foo", () => "bar")
    .set("age", () => 25);

const fooValue = cache.get("foo"); // 类型推断为 string | undefined
const ageValue = cache.get("age"); // 类型推断为 number | undefined
// cache.get("unknownKey"); // 会触发类型错误,因为该键未被设置

实现说明

  • 泛型跟踪键类型:通过Cache类的泛型参数KeyMap,记录所有已设置的键及其对应值的类型。每次调用set方法时,都会返回更新了KeyMap类型的Cache实例,让后续get调用能准确推断类型。
  • 类型安全的get方法:get方法限定参数为KeyMap的键,既保证类型安全,又能自动返回对应的值类型。
  • 移除any类型:将StoreEntry的泛型参数改为明确的类型参数,彻底避免any导致的类型丢失,确保类型推断的准确性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:55:56