打字稿“属性在类型元素上不存在”

lom*_*boo 6 javascript types typescript

我正在使用 Typescript 开始我的旅程。所以我video在我的 Html 和.ts文件这些行中有标记:

...
class KomakhaPlayer {
  private container = ...;
  private video: Element = this.container.getElementsByClassName( 'video' )[ 0 ];
  private controls = ...;

  constructor(){
    this.video.controls = false; // ts error
    ...
  }
}
...
Run Code Online (Sandbox Code Playgroud)

如您所见,this.video具有Element类型,但下this.video.controls面向我抛出 Typescript 错误Property 'controls' does not exist on type 'Element'

临时我将Element类型更改为any,但我想知道如何正确解决此错误并在将来处理类似的问题。提前致谢!

解决方案: 所以正确的方法是这样定义:

private video: HTMLVideoElement = <HTMLVideoElement>this.container.getElementsByClassName( 'video' )[ 0 ];
Run Code Online (Sandbox Code Playgroud)

@deceze在评论中的解释

dec*_*eze 7

Element是一个非常通用的根对象,它确实没有controls属性。请参阅https://developer.mozilla.org/en-US/docs/Web/API/Element。您正在寻找的是一个HTMLVideoElement,它继承自HTMLMediaElement,它具有一个controls属性。

Typescript 是完全正确的:你告诉它你正在使用Element,而 Typescript 警告你 anElement不知道有controls.

  • 不,它不能。`getElementsByClassName('video')` 将准确返回什么元素只在运行时知道,在编译时不知道。在编译时,Typescript 可以推断出的最好的方法是它将是某种“元素”。 (2认同)