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

在工厂函数中用方括号属性访问定义setter出现TypeScript错误

解决TypeScript缓存工厂函数的类型错误

你写的缓存工厂函数中,setItem方法出现Type 'unknown' is not assignable to type 'never'错误,核心原因是TypeScript无法关联key和value的类型:当key被断言为keyof CacheData时,TypeScript只能确定它是accessToken或expiration的联合类型,但value是unknown类型,无法匹配联合类型对应的具体值类型,最终交集为never导致报错。

原代码

interface CacheData {
  accessToken: string;
  expiration: number;
}

function cacheFactory(data: CacheData) {
  const cache: CacheData = data;
  return {
    getItem(key: string) {
      return cache[key as keyof CacheData];
    },
    setItem(key: string, value: unknown) {
      cache[key as keyof CacheData] = value; // 此处报错
    },
  };
}

解决方案1:使用泛型关联键值类型(推荐)

通过泛型K约束key为CacheData的键,同时让value的类型严格对应该键在CacheData中的类型,既保证类型安全,又解决报错:

interface CacheData {
  accessToken: string;
  expiration: number;
}

function cacheFactory(data: CacheData) {
  const cache: CacheData = data;
  return {
    getItem(key: keyof CacheData) {
      return cache[key];
    },
    setItem<K extends keyof CacheData>(key: K, value: CacheData[K]) {
      cache[key] = value;
    },
  };
}

解决方案2:直接使用联合类型约束

如果不想用泛型,也可以将key设为keyof CacheData,value设为CacheData所有值类型的联合类型,但这种方式无法保证key和value的一一对应,类型安全性略低:

interface CacheData {
  accessToken: string;
  expiration: number;
}

function cacheFactory(data: CacheData) {
  const cache: CacheData = data;
  return {
    getItem(key: keyof CacheData) {
      return cache[key];
    },
    setItem(key: keyof CacheData, value: CacheData[keyof CacheData]) {
      cache[key] = value;
    },
  };
}

另外,原代码中getItem的key用string类型再断言为keyof CacheData存在类型安全隐患,直接将key设为keyof CacheData更严谨。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:57:14