Typescript: React event types

前端 未结 8 897
故里飘歌
故里飘歌 2020-11-27 11:50

What is the correct type for React events. Initially I just used any for the sake of simplicity. Now, I am trying to clean things up and avoid use of any<

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 12:27

    The problem is not with the Event type, but that the EventTarget interface in typescript only has 3 methods:

    interface EventTarget {
        addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
        dispatchEvent(evt: Event): boolean;
        removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
    }
    
    interface SyntheticEvent {
        bubbles: boolean;
        cancelable: boolean;
        currentTarget: EventTarget;
        defaultPrevented: boolean;
        eventPhase: number;
        isTrusted: boolean;
        nativeEvent: Event;
        preventDefault(): void;
        stopPropagation(): void;
        target: EventTarget;
        timeStamp: Date;
        type: string;
    }
    

    So it is correct that name and value don't exist on EventTarget. What you need to do is to cast the target to the specific element type with the properties you need. In this case it will be HTMLInputElement.

    update = (e: React.SyntheticEvent): void => {
        let target = e.target as HTMLInputElement;
        this.props.login[target.name] = target.value;
    }
    

    Also for events instead of React.SyntheticEvent, you can also type them as following: Event, MouseEvent, KeyboardEvent...etc, depends on the use case of the handler.

    The best way to see all these type definitions is to checkout the .d.ts files from both typescript & react.

    Also check out the following link for more explanations: Why is Event.target not Element in Typescript?

提交回复
热议问题