Home > Software engineering >  Property 'constructor' does not exist on type 'T'
Property 'constructor' does not exist on type 'T'

Time:11-19

I have a project with next and typescript and I have a generic recursive function in this function typescript says Property 'constructor' does not exist on type '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;
}

CodePudding user response:

The behavior you are seeing here is caused by a slightly out-of-date version of TypeScript.

Narrowing generic types in functions has been quite unreliable for most of the time. But since #49119 was merged in, generic types are intersected with object during control flow analysis when typeof x === "object" is used.

In control flow analysis of typeof x === "object" expressions, generic types are intersected with object and/or null in the true branch (typeof checks for other types already produce intersections in a similar manner).

#49119 was introduced in TypeScript version 4.8; so upgrading your version would be your best bet to resolve this issue.

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

  • Related