!对象方法后打字稿中的运算符 [英] ! operator in typescript after object method

查看:22
本文介绍了!对象方法后打字稿中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有方法 getY() 的对象 X 返回一个带有方法 a() 的对象 Y代码>,在打字稿中.像这样的表达是什么意思:

I have an object X with a method getY() returning an object Y with a method a(), in typescript. What does it mean an expression like this one:

X.getY()!.a()

我猜 ! 运算符是用来检查 null 的,但它具体是如何工作的呢?语言中在哪里定义?

I guess the ! operator is used to check against null, but how does it work concretely? Where is defined in the language?

推荐答案

它被称为非空断言运算符",它告诉编译器 x.getY() 不为空.

It's called the "Non-null assertion operator" and it tells the compiler that x.getY() is not null.

这是一个新的 typescript 2.0 功能,您可以在 新内容 页面,内容如下:

It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:

一个新的!后缀表达式运算符可用于断言其操作数在类型为非空且非未定义的上下文中checker 无法得出这个事实.具体来说,操作X!生成 x 类型的值,排除 null 和 undefined.类似于形式为 x 和 x 作为 T 的类型断言,!非空断言运算符在发出的JavaScript 代码.

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
    // Throw exception if e is null or invalid entity
}

function processEntity(e?: Entity) {
    validateEntity(e);
    let s = e!.name;  // Assert that e is non-null and access name
}

<小时>

编辑

记录此功能存在一个问题:记录非空断言运算符 (!)

这篇关于!对象方法后打字稿中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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