5
轉到https://www.typescriptlang.org/play/index.html和粘貼:類型不能用作索引類型
let userTypes = {};
let keys = Object.keys[userTypes];
收到錯誤:
error TS2538: Type '{}' cannot be used as an index type.
爲什麼?
轉到https://www.typescriptlang.org/play/index.html和粘貼:類型不能用作索引類型
let userTypes = {};
let keys = Object.keys[userTypes];
收到錯誤:
error TS2538: Type '{}' cannot be used as an index type.
爲什麼?
Object.keys
返回屬性數組。你不能使用一個對象來索引一個數組;您必須使用數字來表示從數組起始處的偏移量。
作爲等價例子,你能指望這個代碼做?:
var a = [1, 2, 3, 4]
console.log(a[{}]);
這是荒謬的。
編輯: 在閱讀OP的評論並再次查看代碼後,我意識到我的評估是錯誤的。雖然a問題是,原始代碼試圖使用對象字面量索引keys
函數,但真正的問題是使用方括號而不是括號。這將工作:
let keys = Object.keys(userTypes);
它要求keys
與userTypes
,而不是與它的索引。
我希望它返回undefined ...:D –
現在我看到了令人尷尬的錯字...謝謝... –
應該是'Object.keys(userTypes)' –