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

TypeScript类型转换错误:Extract<keyof T, string>转K类型问题排查与解决

TypeScript对象属性移除函数的类型错误解决方法

需求与原始实现

我需要编写一个TypeScript函数,接收对象和需忽略的属性键数组,返回移除这些属性后的对象。最初实现的代码如下:

interface Obj {
  [key: string]: any;
}

function transpose<T extends Obj, K extends keyof T>(obj: T, ignore: K[]): Pick<T, Exclude<keyof T, K>> {
  const result: Pick<T, Exclude<keyof T, K>> = {} as Pick<T, Exclude<keyof T, K>>;
  for (const prop in obj) {
    if (!ignore.includes(prop as K)) {
      result[obj[prop]] = prop as Exclude<keyof T, K>;
    }
  }
  return result;
}

遇到的类型错误

函数可以正常运行,但TypeScript会抛出如下类型错误:

Conversion of type 'Extract<keyof T, string>' to type 'K' may be a mistake because neither type sufficiently overlaps with the other. 'unknown' first.

另外,当尝试向ignore数组添加不属于该对象的新键时,也会触发类似错误,我期望编译器允许这种操作但遇到了报错。

优化后的解决方案

已经找到解决办法,优化后的代码如下:

interface Obj {
  [key: string]: any;
}

function transpose<T extends Obj, K extends keyof T>(obj: T, ignore: K[]): { [key: string]: T[keyof T] } {
  const result: { [key: string]: T[keyof T] } = {};
  for (const prop in obj) {
    if (!ignore.includes(prop as unknown as K)) {
      result[obj[prop] as string] = obj[prop];
    }
  }
  return result;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 07:17:02