打字稿“属性在类型元素上不存在"; [英] Typescript "Property does not exists on type Element"

查看:30
本文介绍了打字稿“属性在类型元素上不存在";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm starting my journey with Typescript. So I have video tag in my Html and in .ts file these lines:

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

  constructor(){
    this.video.controls = false; // ts error
    ...
  }
}
...

正如你所看到的 this.videoElement 类型,但在 this.video.controls 下方给我一个 Typescript 错误 元素"类型不存在属性控件".

As you can see this.video has Element type, but below this.video.controls throws me a Typescript error Property 'controls' does not exists on type 'Element'.

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

Temporary I changed Element type to any, but I want to know how properly solve this error and handle similar in future. Thanks in advance!

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

SOLUTION: So the right approach is defining like this:

private video: HTMLVideoElement = <HTMLVideoElement>this.container.getElementsByClassName( 'video' )[ 0 ];

@deceze 在下面评论中的解释

推荐答案

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

Element is a very generic root object which indeed does not have a controls attribute. See https://developer.mozilla.org/en-US/docs/Web/API/Element. What you're looking for is an HTMLVideoElement, which inherits from HTMLMediaElement, which has a controls attribute.

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

Typescript is entirely correct: you told it you're working with an Element, and Typescript warns you that an Element is not known to have controls.

这篇关于打字稿“属性在类型元素上不存在";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆