![](/img/trans.png)
[英]Typescript: Type 'undefined' cannot be used as an index type.ts(2538)
[英]TS2538 Type 'undefined' cannot be used as an index type. when check assigned to variable
我收到TS錯誤:
TypeScript錯誤:類型“未定義”不能用作索引類型。 TS2538
對於這個簡單的函數(根據提供的索引從數組中獲取對象):
const myArr: Array<object> = [{name: 'John'}, {name: 'Tom'}]
function getData(index?: number) {
const isIndex : boolean = typeof index !== 'undefined';
return isIndex ? myArr[index] : {};
}
對我來說更神秘的是,當我將其更改為:
function getData(index?: number) {
return typeof index !== 'undefined' ? myArr[index] : {};
}
一切都像魅力 - 為什么?
由於代碼流中的某些間接性,Typescript不會像我們期望的那樣遵循代碼分析。 所以這就是用戶定義類型警衛進入圖片營救的地方。
function isUndefined(index: any): index is boolean {
return typeof index === "undefined";
}
function getData(index?: number) {
return isUndefined(index) ? myArr[index] : {};
}
因為index
在getData函數中是可選的,所以它可能是undefined
,所以你的第二種方法是有效的。
類型保護不適用於中間變量。 你必須直接測試變量:
function getData(index?: number) {
return index !== undefined ? myArr[index] : {};
}
要么:
function getData(index?: number) {
if (index === undefined)
return {};
return myArr[index]
}
另見: 關於型號保護的手冊中的文檔 。
注意:現在不需要typeof index !== 'undefined'
: ES2015 / 2016的'typeof varName ==='undefined`方式?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.