2

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?

2 Answers 2

2

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;
};
Sign up to request clarification or add additional context in comments.

Comments

0

Is the following code snippet, what you are looking for?

class Observer extends HTMLInputElement{
    Update: any;
}

var check:Observer = <Observer>document.createElement("input");

check.Update = function(value) {
    this.checked = value;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.