简体   繁体   中英

how to stop the typescript error `Property 'play' does not exist on type 'HTMLElement'.ts(2339)`

H, I have this native javascript line in my React/typescript app and as first it was erroring that Object is possibly 'null'. so I have added the ! between the selector method and the play() method, however, I got this error now saying Property 'play' does not exist on type 'HTMLElement'.ts(2339 How I can fix this with typeScript,m thanks

  const handleSound = () => {
    document.getElementById("helloMessage")!.play();
}

You can solve the null issue with an if .

Casting will fix the play does not exist error

const handleSound = () => {
  const element = document.getElementById("helloMessage") as HTMLVideoElement;
  if (!element) {
    throw new Error('Missing element')
  }
  element.play();
}

Also, you should never use getElementById in React

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM