Why is Event.target not Element in Typescript?

后端 未结 8 890
情歌与酒
情歌与酒 2020-12-01 03:55

I simply want to do this with my KeyboardEvent

var tag = evt.target.tagName.toLowerCase();

While Event.target is of type EventTarget it doe

8条回答
  •  余生分开走
    2020-12-01 04:43

    Using typescript, I use a custom interface that only applies to my function. Example use case.

      handleChange(event: { target: HTMLInputElement; }) {
        this.setState({ value: event.target.value });
      }
    

    In this case, the handleChange will receive an object with target field that is of type HTMLInputElement.

    Later in my code I can use

    
    

    A cleaner approach would be to put the interface to a separate file.

    interface HandleNameChangeInterface {
      target: HTMLInputElement;
    }
    

    then later use the following function definition:

      handleChange(event: HandleNameChangeInterface) {
        this.setState({ value: event.target.value });
      }
    

    In my usecase, it's expressly defined that the only caller to handleChange is an HTML element type of input text.

提交回复
热议问题