Nickon
Nickon

Reputation: 10146

Undefined property in TypeScript

I have a problem with events.

I have two interfaces created:

export interface IEEvent extends JQueryEventObject, MSEventObj {
    preventDefault: () => void;
    cancelBubble: bool;
}

export interface IEElement extends HTMLElement {
    click: (event?: IEEvent) => void;
    onmousedown: (event?: IEEvent) => void;
    onmousemove: (event?: IEEvent) => void;
    onmouseup: (event?: IEEvent) => void;
}

I try to set onmousedown\move\up props and I get an error...

public static StopPropagation(element: HTMLElement): void {
    (<IEElement> element).onmousedown = StopPropagationHandler; // error here
    (<IEElement> element).click = StopPropagationHandler; // error here
    (<IEElement> element).onmouseup = StopPropagationHandler; // error here
}

private static StopPropagationHandler(e?: IEEvent): void {
    if (typeof (e) === "undefined") {
        e = <IEEvent> window.event;
    }
    if (typeof (e.preventDefault()) !== "undefined") { // error here
        e.preventDefault(); // error here
    }
    e.cancelBubble = true;
}

Properties

Method

How to get rid of these errors?

Upvotes: 1

Views: 4192

Answers (1)

Joseph Lennox
Joseph Lennox

Reputation: 3249

It sounds like when the exception happens StopPropagation is at the top of your call stack. If you examine this inside of a debugger I suspect element would be undefined. You may consider revising your code to handle this or throw an exception if that's the case. Examples:

To allow undefines:

public static StopPropagation(element: HTMLElement): void {
    if (element) {
        (<IEElement> element).onmousedown = StopPropagationHandler; // error here
        (<IEElement> element).click = StopPropagationHandler; // error here
        (<IEElement> element).onmouseup = StopPropagationHandler; // error here
    }
}

To disallow undefines:

public static StopPropagation(element: HTMLElement): void {
    if (!element) {
        throw new Error("Null argument exception. An element must be provided.");

    (<IEElement> element).onmousedown = StopPropagationHandler; // error here
    (<IEElement> element).click = StopPropagationHandler; // error here
    (<IEElement> element).onmouseup = StopPropagationHandler; // error here
}

Upvotes: 1

Related Questions