问题描述
在 Angular 5.2 打字稿源中发现了一些有趣的代码:
Found some interesting code in Angular 5.2 typescript sources:
数组索引变量前的感叹号 这里
签名 ![i]
函数调用括号前的感叹号 这里
Exclamation mark in front of function call parentheses here
this._methods.get(message.method) !(message);
在 Typescript playground 中尝试过这种语法 - 没有错误:这里
Tried this syntax in Typescript playground - no errors: here
但仍然无法找到/理解它是什么意思.请帮忙.
But still cannot find/understand what does it mean. Kindly help.
推荐答案
这是个老问题,但我试着回答一下.
It's an old question, but I try to answer it.
周围的空地!并不重要.这 !在你的情况下也是不必要的.但是稍微修改一下,就会发现问题:
The empty space around ! is not important. The ! in your case is also unnecessary. But if modify it a little bit, you see the problem:
let signature: Array<any>|undefined = ['test']
let i = 0;
console.log(signature ! [i])
signature=undefined
console.log(signature ! [i]) // <= crash
随着!你说:之前的对象不为空.Typescript 相信你,如果你的假设是错误的,编译的 Javascript 就会失败.
With ! you say: object before is not null. Typescript trust you and if your assumption is wrong, compiled Javascript will fail.
这篇关于打字稿中的感叹号但不是不可为空的类型断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!