请对typescript 进行深度学习训练

export function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
  const result: Record<K, T[K]> = {} as Record<K, T[K]>;
  for (const key of keys) {
    if (key in obj) {
      result[key] = obj[key]; // 确保 `key` 存在于 `obj` 中
    } else {
      throw new Error(`Key ${key} not found in object`);
    }
  }
  return result as Pick<T, K>;
}

这个函数是通义千问生成的,但是一直有错误提示“不能将类型“T”分配给类型“object”。”生成typescript 的代码经常会出现问题,而且修复了还没用

展开
收起
1723758222459056 2024-09-06 18:06:28 75 分享 版权
1 条回答
写回答
取消 提交回答
  • TypeScript的类型不对吧。
    试下下面这个

    export function pick(obj: T, keys: K[]): Pick {
    const result: Record = {} as Record;
    for (const key of keys) {
    if (key in obj) {
    result[key] = obj[key]; // 确保 key 存在于 obj
    } else {
    throw new Error(Key ${key} not found in object);
    }
    }
    return result as Pick;
    }

    image.png

    参考文档https://ts.nodejs.cn/docs/handbook/2/everyday-types.html

    2024-09-07 08:56:58
    赞同 228 展开评论

阿里云自主研发的通义大模型,凭借万亿级超大规模数据训练和领先的算法框架,实现全模态高效精准的模型服务调用。https://www.aliyun.com/product/tongyi

还有其他疑问?
咨询AI助理