'!'之间的区别和 '?'在TypeScript中 [英] Difference Between '!' and '?' in TypeScript

查看:148
本文介绍了'!'之间的区别和 '?'在TypeScript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class Employee {
  firstName: string;
  lastName!: string;
  middleName?: string;
}

Employee 类的这3个不同字段有什么区别?

What is the difference in these 3 different fields of Employee class?

实时实施例

推荐答案

该位置该位置的确定的分配断言.有点像非null断言运算符,但用于属性(也可以用于变量)而不是表达式.

The ! in that position is the definite assignment assertion. It's sort of a declaration-level version of the non-null assertion operator, but used on a property (can also be used on variables) rather than on an expression.

在此示例中有两个错误,或者可以说是三个错误:

There are two — or arguably three — errors in that example:

  1. Class 应该是 class ;JavaScript和TypeScript区分大小写.

  1. Class should be class; JavaScript and TypeScript are case-sensitive.

您需要在 firstName 上使用初始化程序(或无条件分配给它的构造函数).

You need an initializer on firstName (or a constructor that assigns to it unconditionally).

lastname 上的告诉TypeScript,肯定会分配 lastName ,从而消除了您遇到的错误类型 firstName ,但实际上(在示例中)实际上并没有执行 使用的赋值操作,即保证您知道TypeScript确实在执行操作./p>

The ! on lastName tells TypeScript that lastName will definitely be assigned, suppressing the kind of error you're getting for firstName, but nothing (in the example) actually does the assignment that using ! there promises TypeScript you know for sure you're doing.

您链接的代码稍后处理上面的#1和#2,但是不是#3.TypeScript不会警告 lastName 从未被分配,并假定其值为字符串,而实际上它不存在,因此读取其值将导致 undefined .

The code you linked later deals with #1 and #2 above, but not #3. TypeScript won't warn that lastName is never assigned and assumes its value is a string, when in fact it's not there and so reading its value will result in undefined.

这篇关于'!'之间的区别和 '?'在TypeScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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