检查Typescript

时间:2018-04-17 05:22:21

标签: reactjs typescript

我正在尝试检查我的React / Typescript组件中的params的类型

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

如何编写if / else条件?

2 个答案:

答案 0 :(得分:2)

您可以使用event.type属性。 有关详细说明,请参阅这些文档SyntheticEvent

答案 1 :(得分:1)

React.MouseEventReact.KeyboardEvent都定义为接口,因此这些类型没有运行时表示。我们可以创建一个类型保护来区分类型,如果对象符合接口,我们可以使用对象上定义的属性进行实际测试:

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
    }
}