关于TS编写深拷贝方法出现ts类型报错

```

```### 问题描述

问题出现的环境背景及自己尝试过哪些方法

想用ts编写一个简单的深拷贝方法, 但是ts的类型校验不通过, 求大佬给解答下我这个错误怎么出现的, 应该怎么解决吖!!!!!

相关代码

function deepCopy (sourceData: T): T {
if (Array.isArray(sourceData)) {
return sourceData.map(item => deepCopy(item)) as T;
}
const obj: T = {} as T;
for(let key in sourceData) {
if ((typeof sourceData[key] === 'object') && sourceData[key] !== null) {
obj[key] = deepCopy(sourceData[key]);
} else {
obj[key] = sourceData[key];
}
}
return obj;
}
粘贴代码文本(请勿用截图)

你期待的结果是什么?实际看到的错误信息又是什么?

Conversion of type 'any[]' to type 'T' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. 'T' could be instantiated with an arbitrary type which could be unrelated to 'any[]'

阅读 7.3k
2 个回答
function deepCopy<T extends Array<T> | any>(sourceData: T): T {
    if (Array.isArray(sourceData)) {
        return sourceData.map(item => deepCopy(item)) as T
    }
    const obj: T = {} as T
    for (let key in sourceData) {
        if ((typeof sourceData[key] === 'object') && sourceData[key] !== null) {
            obj[key] = deepCopy(sourceData[key])
        } else {
            obj[key] = sourceData[key]
        }
    }
    return obj
}

deepCopy({ name: '小明 ', age: 15 })
deepCopy([100, 666, 23333])

这样可?

泛型函数名字后面应该加上<T>,只是ts认为把数组转为T类型通常是错误,所以就报了个错,下面只是一个解决方案。

function deepCopy<T extends unknown>(sourceData: T): T {
  if (Array.isArray(sourceData)) {
  return sourceData.map(item => deepCopy(item)) as T;
  }
  const obj: T = {} as T;
  for(let key in sourceData) {
  if ((typeof sourceData[key] === 'object') && sourceData[key] !== null) {
  obj[key] = deepCopy(sourceData[key]);
  } else {
  obj[key] = sourceData[key];
  }
  }
  return obj;
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题