属性'constructor'在类型 'T' 上不存在



我有一个带有next和typescript的项目,我在这个函数中有一个泛型递归函数typescript说属性'constructor'不存在类型'T'

this is my function

export const deepClone = <T>(obj: T):T => {
if (obj === null || typeof (obj) !== 'object') {
return obj;
}
let temp;
if (obj instanceof Date) {
temp = new Date(obj); //or new Date(obj);
} else if (obj) {
temp = obj.constructor();
}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
temp[key] = deepClone(obj[key]);
}
}
return temp;
}

你在这里看到的行为是由一个有点过时的TypeScript版本引起的。

在大多数情况下,函数中的窄化泛型类型是相当不可靠的。但是,由于#49119被合并,当使用typeof x === "object"时,在控制流分析中,泛型类型与object相交。

在控制流程分析中typeof x === "object"表达式、泛型类型在true分支中与object和/或null相交(对其他类型的typeof检查已经以类似的方式产生相交)。

#49119是在TypeScript 4.8版中引入的;所以升级你的版本将是你最好的办法来解决这个问题。

export const deepClone = <T>(obj: T):T => {
if (obj === null || typeof obj !== 'object') {
return obj;
}
obj
//  ^? obj: T & object
obj.constructor();
}

Working Playground on 4.8.4

最新更新