!: 在打字稿中是什么意思? [英] What does !: mean in Typescript?

查看:38
本文介绍了!: 在打字稿中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$refs!: {
    helloComponent: Hello
}

https://github.com/vuejs/vue-class-component/blob/master/example/App.vue

推荐答案

当 TypeScript 认为某些属性、变量将为 nullundefined 时,会出现这种情况.但是如果你确定这个变量不能为空,那么你可以使用这个运算符.

There will be a scenario when TypeScript believes that certain property, variable will be null or undefined. But if you are sure that this variable cannot be null, then you can use this operator.

考虑示例:

let a = document.getElementById('hello');

if (a) {
    a.style.width = '100px';
}

TypeScript 假定变量 a 可能为 null,因为无法保证该元素存在.所以在你可以访问那个变量之前,你已经放入了 if 守卫.但是如果你知道你的应用程序总是会有一个 id 为 #hello 的 HTML 元素,那么你可以将上面的代码重写为:

TypeScript assumes that variable a may be null since there is no guarantee for this element to exists. So before you can access that variable, you have put in if guard. But if you know that your application is always going to have an HTML element with id #hello, then you can rewrite above code as:

const a = document.getElementById('hello');

a!.style.width = '100px';

上面的代码更易读,更简洁.在 https://www.typescriptlang.org 阅读更多/docs/handbook/release-notes/typescript-2-0.html

The above code is more readable and less verbose. Read more here at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html

@Simon 在技术上正确的评论:具体来说,操作 x!生成 x 类型的值,排除 null 和 undefined.

Technically correct comment by @Simon: Specifically, the operation x! produces a value of the type of x with null and undefined excluded.

这篇关于!: 在打字稿中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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