TypeScript 中的类型断言运算符是什么? [英] What is the type assertion operator for in TypeScript?

查看:29
本文介绍了TypeScript 中的类型断言运算符是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

规范并没有过多说明类型断言运算符在 TypeScript 中的哪些方面可能会有所帮助.我的代码中不需要它.所以我很好奇它应该解决什么样的问题.有什么想法吗?

The spec doesn't say much about where the type assertion operator might be helpful in TypeScript. I didn't need it in my code. So I am curious what sort of problems it is supposed to solve. Any ideas?

推荐答案

它有点像 类型转换 但是因为它没有运行时支持(它只是一个编译时断言)TypeScript 选择调用它是类型断言".考虑这个例子:

It's somewhat like type casting however as it does not come with runtime support (its a compile time assertion only) TypeScript choses to call it 'Type Assertion'. Consider this example :

var element1 = document.getElementById('canvas'); // Determined to be HTMLElement
element1.getContext('2d'); // ERROR as it is HTMLElement 



// Determined to be canvas due to your assertion
var element2 = <HTMLCanvasElement>document.getElementById('canvas'); 
element2.getContext('2d'); // Valid 

每当 typescript 类型推断由于不兼容的推断类型而阻止您分配东西时,您将需要它.

You will need it whenever typescript type inference would prevent you to assign things around due to incompatible inferred types.

这篇关于TypeScript 中的类型断言运算符是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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