function getType(target: unknown) {
return Object.prototype.toString.call(target).slice(8, -1);
}
/**
* 深度克隆
*/
export function deepClone<T>(target: T): T {
const type = getType(target);
if (type === 'Array') {
// @ts-ignore
const result = [];
// @ts-ignore
target.forEach((value, index) => {
result[index] = deepClone(value);
});
// @ts-ignore
return result;
}
if (type === 'Object') {
const result = {};
Object.keys(target).forEach((key) => {
// @ts-ignore
result[key] = deepClone(target[key]);
});
// @ts-ignore
return result;
}
if (type === 'RegExp') {
const reFlags = /\w*$/;
// @ts-ignore
const result = new target.constructor(target.source, reFlags.exec(target));
// @ts-ignore
result.lastIndex = target.lastIndex;
return result;
}
return target;
}
上面实现了一个简单的深度克隆,在 typescript 中会报类型错误,目前是使用 // @ts-ignore 屏蔽了类型错误。
如何在实现一样的功能下,不让 typescript 报类型错误
你用typeof试试,参考这个文章 https://www.coding-time.cn/ts里面有一篇类型守卫或者类型收窄的解