Search code examples
typestypescriptextendtypescript1.6

Copy a object properties to another in TypeScript, cause error TS2339


I use a extend() function to extend a object:

function extend(obj: Object, extension: Object) {
    for (var key in obj) {
        try {
            extension[key] = obj[key];
        } catch (e) {
            console.error(e);
        }
    }
}

And there is a class Observer() hava a method Update() and a object check which is HTMLInputElement type.

class Observer {
    Update(value) { }
}
var check:HTMLInputElement = document.createElement("input");

I use extend() function to extend checkbox,so it would have the method Update().

extend(new Observer(), check);
check.Update = function(value) {
    this.checked = value;
}

And then cause error TS2339:Property 'Update' does not exist on type 'HTMLInputElement' enter image description here

How to Fixed this error? Change the extend() function?


Solution

  • Might be a good scenario for an intersection type?

    function extend<T, U>(obj: T, extension: U) {
        Object.keys(obj).forEach((key) => {
            extension[key] = obj[key];
        });
    
        return extension as T & U;
    }
    
    var check: HTMLInputElement;
    var extended = extend(new Observer(), check);
    
    // example HTMLInputElement property use
    extended.attributes;
    // no compile error here either:
    extended.Update = function(value) {
        this.checked = value;
    };