簡體   English   中英

`?` 在某些對象屬性之前是什么意思? 為什么我的 ts 文件不接受它?

[英]what `?` means before some object attribute? and why my ts file doesn´t accept it?

當我有一個可能未定義的對象或所需對象以外的對象時,我總是在 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

它在組件的打字稿部分不起作用,因為打字稿不支持它。

唯一的用途? 打字稿中的變量是指定方法的參數是可選的:

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#可選鏈

Typescript 3.7+ 具有可選鏈接( https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

有了這個,表達式if (object?.foo) {}是有效的語法 - 如果object未定義或為空,條件將解析為未定義。

檢查您的打字稿版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM