Checking parameter types in Typescript

I'm trying to check the type of my params in my React/Typescript component

foo(e: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>) {
    if(e is mouse event) {
        //do something
    }
    else if (e is KeyboardEvent) {
        //do something else
    }
}

How can I write the if/else conditions?

2 answers

  • answered 2018-04-17 05:22 Titian Cernicova-Dragomir

    React.MouseEvent and React.KeyboardEvent are both defined as interfaces and thus there is no runtime representation for these types. We can create a type-guard to differentiate between the types, and we can use properties defined on the object actually test if the object conforms to the interface:

    function isMouseEvent<T>(e: any | React.MouseEvent<T>) : e is React.MouseEvent<T> {
        let eMouse = e as React.MouseEvent<T>;
        // Can test for other properties as well
        return eMouse && typeof eMouse.pageX === "number" && typeof eMouse.pageY === "number"
    }
    
    function isKeyboardEvent<T>(e: any | React.KeyboardEvent<T>) : e is React.KeyboardEvent<T> {
        let eKey= e as React.KeyboardEvent<T>;
        // Can test for other properties as well
        return eKey&& typeof eKey.charCode === "number" && typeof eKey.key === "string"
    }
    
    function foo(e: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>) {
        if(isMouseEvent(e)) {
            e // will be React.MouseEvent<HTMLElement>
        }
        else {
            e // will be React.KeyboardEvent<HTMLElement> by exclusion, or we could use the other type guard
        }
    }
    

  • answered 2018-04-17 05:22 Shahid Peerzade

    You can make use of event.type property. for more detail explanation please refer these docs SyntheticEvent