我有一段代碼,看起來像這樣:打字稿 - 返回一個空數組沒有聲明一個局部變量
let emptyArray: string[]
if (context == null)
return emptyArray
有沒有辦法做到這一點:
if (context == null)
return new string[]
我有一段代碼,看起來像這樣:打字稿 - 返回一個空數組沒有聲明一個局部變量
let emptyArray: string[]
if (context == null)
return emptyArray
有沒有辦法做到這一點:
if (context == null)
return new string[]
您也可以鍵入斷言返回什麼讓編譯器知道你是返回一個string[]
而不僅僅是一個數組。如果你不想在其他地方定義它。
if (context == null)
return [] as string[];
當然,空數組對於任何類型的數組都是有效的值。
這不完全明確你想要什麼,因爲沒有上下文,例如誰返回空數組,誰得到這個結果,但它很容易就這樣做:
function fn(context: any): string[] {
if (context == null) {
return [];
}
...
}
也許我不明白你的問題,但是這似乎是有效的打字稿,我在我的編輯器:
getValue(context): Array<String> {
if(context==null) {
return [];
}
}
順便說一句,請注意你在第一個例子中返回'undefined',因爲你沒有初始化emptyArray。在另一個例子中,它看起來像你想返回一個空數組。 – Alex