简体   繁体   English

TypeScript 中带有箭头 < type > 的赋值是什么意思?

[英]What does assignment with arrows < type > mean in TypeScript?

I know that colon sets the type for the variable, but what does assignment with arrows mean with the type provided?我知道冒号设置了变量的类型,但是对于所提供的类型,带箭头的赋值意味着什么?

const mainVideo: HTMLVideoElement = <HTMLVideoElement> document.getElementById('mainVideo');

I was using mainVideo : HTMLVideoElement = document.getElementById('mainVideo') at first, but it wouldn't let me use any of the methods on the element, but assigning mainVideo with the arrows makes everything work.我一开始使用的是 mainVideo : HTMLVideoElement = document.getElementById('mainVideo') ,但它不允许我使用元素上的任何方法,但是用箭头分配 mainVideo 使一切正常。 Wondering why that is and what's it called.想知道为什么会这样,它叫什么。

It's called type assertion .这叫做类型断言

Think of type assertion as a way to make an entity type more specific by overriding it.将类型断言视为一种通过覆盖实体类型使其更具体的方法。

// this is an Element
let element = document.querySelector("#list");


// but I can make it more specific, by overriding its type
let element = <HTMLElement> document.querySelector("#list");

You can also use this other syntax:您还可以使用其他语法:

let element = document.querySelector("#list") as HTMLElement;

Be careful.当心。 You don't want type assertion everywhere, just where it's necessary.您不希望在任何地方都使用类型断言,只在需要的地方使用。 Otherwise, your code may need refactoring.否则,您的代码可能需要重构。

Also, not always you can do type assertion.此外,并非总是可以进行类型断言。 Only when either types sufficiently overlaps with the other.只有当任何一种类型与另一种类型充分重叠时。 So, if you write this:所以,如果你这样写:

let element = document.querySelector("#list") as String;

VSCode says: VSCode 说:

Conversion of type 'Element' to type 'String' may be a mistake because neither type sufficiently overlaps with the other.将 'Element' 类型转换为 'String' 类型可能是错误的,因为这两种类型与另一种类型都没有足够的重叠。

Type 'Element' is missing the following properties from type 'String': charAt, charCodeAt, concat, indexOf, and 34 more “元素”类型缺少“字符串”类型中的以下属性:charAt、charCodeAt、concat、indexOf 和 34 个更多

One way to make sure you can do this weird assertion is by converting the expression to unknown first:确保您可以执行此奇怪断言的一种方法是首先将表达式转换为unknown

let element = document.querySelector("#list") as unknown as String;

Even though it works, make sure YOU KNOW it's worth it.即使它有效,请确保您知道这是值得的。


What happend in your use case is that getElementById is a method which returns an HTMLElement and not, specifically , an HTMLVideoElement .发生了什么在你的使用情况是getElementById是它返回一个方法HTMLElement ,而不是,具体而言HTMLVideoElement

// it could be HTMLDivElement or HTMLInputElement, for example.
Document.getElementById(elementId: string): HTMLElement

Hence, when you did type assertion, you were basically saying:因此,当您进行类型断言时,您基本上是在说:

I KNOW this method will return a more specific version of HTMLElement , called HTMLVideoElement .我知道这个方法将返回一个更具体的HTMLElement版本,称为HTMLVideoElement

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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