javascript - `?` 在某些对象属性之前是什么意思?为什么我的 ts 文件不接受它?

标签 javascript html angular typescript conditional-statements

我一直使用这种行为以 Angular 展示在这里*ngIf当我有一个可能未定义或所需对象以外的对象时的指令

<div *ngIf="object?.foo">
  ...
</div>

我知道这有效,但不知道为什么...

但是当我尝试在我的 TypeScript 中的 if 上使用它时像下面的 angular 文件给我两个不同的错误 TS1005, TS1109 ,在我尝试使用此行为的每一行上交替使用。
if(object?.foo){} // error TS1109
if(object?.foo){} // error TS1005
if(object?.foo){} // error TS1109
if(object?.foo){} // error TS1005

我在这个项目中使用 Angular 7.3.9

最佳答案

它在您的模板中工作的原因是因为 angular 会将其计算为以下表达式:

<div *ngIf="object && object.foo">

如果对象为空,这将防止在对象上调用属性的错误。

文档链接:https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths

它在组件的 typescript 部分不起作用,因为 typescript 不支持它。

唯一使用? typescript 中的变量是指定方法的参数是可选的:
function myFunc(mandatoryParam: any, optionalParam?: any) {
    ...
}

myFunc('hello'); // Will work
myFunc('hello', 'world'); // Will work too

正如对此答案的评论中所述,TypeScript 将在 3.7 版本中添加对 angular 模板语法的支持:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

关于javascript - `?` 在某些对象属性之前是什么意思?为什么我的 ts 文件不接受它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60452461/

相关文章:

javascript - 在 javascript 中处理嵌套 promise 树的最快方法?

html - 如何使用 HTML5 和 CSS3 将 .ogg 视频放在 .png 图像后面?

div 和数据完全渲染后的 Angular 设置滚动位置

c# - 我如何将 gzip 用于我的 Angular 项目?

javascript - 汉字和 onkeypress 事件

javascript - ExtJS 和 Internet Explorer : Layout corruption with scrollbars

html - 如何使用 CSS 去除 html 表格内的白线

javascript - Angular 5 : Passing an array from child to parent component

javascript - 删除促销代码后最终金额不变

javascript - 非法第一个字符的正则表达式