javascript - 在介面上的字串型別索引簽名不被識別(typescript)
我有這段程式碼:
const sectionInstance: FieldValues = sectionInstances[i]
for (const field in sectionInstance) {
console.log(sectionInstance[field])
}
`field` 這裡當然是一個字串。以下是 `FieldValues` 的類型定義:
export interface FieldValues = {
[key: string]: FieldValue;
}
我仍然收到這個錯誤:
Element 隱含地具有「any」類型,因為無法使用類型為「string」的表達式來索引類型「FieldValues」。在類型「FieldValues」上未找到帶有「string」類型參數的索引簽名。Vetur(7053)
我不是已經為 interface FieldValues 宣告了一個類型為 'string' 的索引簽名了嗎?為什麼我會得到這個錯誤?
答案#1
只需從介面定義中移除 =。
請看一下操場
interface FieldValues {
[key: string]: FieldValue;
}
...
const sectionInstance: FieldValues = sectionInstances[i];
for (const field in sectionInstance) {
console.log(sectionInstance[field]);
}
答案#2
據我所知,Typescript 無法從 [key: string] 推斷鍵的類型。它僅在你試圖概括某些鍵(可能除其他鍵外)可能存在且為字串類型時才有用。TS 無法保證你在 for 中訪問的鍵是你在 [key: string] 中使用的 string 類型。你應該明確地指出它。
