簡體   English   中英

我可以在打字稿中定義字符串數組和未定義的數組嗎?

[英]Can I define array of strings and undefined in typescript?

我在打字稿中定義了以下數組: let ids: string[] = []; . 然后,當我嘗試推送一個 id(可能未定義)時,出現編譯錯誤: ids.push(id); 給我以下編譯錯誤:

TS2345:“字符串”類型的參數 | undefined' 不能分配給'string' 類型的參數。 類型“未定義”不可分配給類型“字符串”。

我可以創建字符串數組和未定義的數組嗎?

是的:

let ids: (string | undefined)[] = [];

我懷疑您可能在編譯器配置中啟用了strictstrictNullChecks標志(通過調用tsc時的命令行或在tsconfig.json文件中)。

在嚴格的空值檢查模式下,空值和未定義值不在每種類型的域中,並且只能分配給它們自己和任何類型(一個例外是未定義也可以分配給 void)。 [ 1 ]

作為一個例子,我們可以使用這個示例代碼重現這個,

let ids: string[] = [];
let x: string | undefined;
x = Math.random() > 0.5 ? undefined : 'hello';
ids.push(x);

在這里,編譯器無法判斷xundefined還是string (請注意,如果您執行x = 'hello' ,則編譯器可以靜態檢查x在運行時是否undefined

我們將在啟用strict標志的情況下編譯它(這也啟用strictNullChecks標志)

我們得到以下編譯器錯誤

src/main.ts:4:10 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

4 ids.push(x);
           ~

因此,您可能希望按照另一個答案的建議將ids變量定義為(string | undefined)[]或考慮禁用嚴格標志。

另一種可能的解決方案是使用! 非空斷言運算符)運算符繞過編譯器(但您在許多情況下故意忽略潛在錯誤,因為編譯器無法再幫助您),

ids.push(x!);

暫無
暫無

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

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