And*_*che 20 dictionary node.js typescript google-cloud-firestore
我来自移动应用程序开发,对打字稿没有太多经验。如何声明 [string:any] 形式的地图对象?
错误出现在行:map[key] = value;
元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“Object”类型。
在类型“Object”.ts(7053) 上找不到带有“string”类型参数的索引签名
var docRef = db.collection("accidentDetails").doc(documentId);
docRef.get().then(function(doc: any) {
if (doc.exists) {
console.log("Document data:", doc.data());
var map = new Object();
for (let [key, value] of Object.entries(doc.data())) {
map[key] = value;
// console.log(`${key}: ${value}`);
}
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
} }).catch(function(error: any) {
console.log("Error getting document:", error);
});
Run Code Online (Sandbox Code Playgroud)
Tim*_*rry 62
您通常不想使用new Object(). 相反,map像这样定义:
var map: { [key: string]: any } = {}; // A map of string -> anything you like
Run Code Online (Sandbox Code Playgroud)
如果可以,最好any用更具体的东西替换,但这应该是一开始的。
您需要声明一个记录类型
var map: Record<string, any> = {};
Run Code Online (Sandbox Code Playgroud)
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeystype
正如@Tim Perry 上面提到的,直接使用对象。我建议您建立自己的词典。
declare global {
type Dictionary<T> = { [key: string]: T };
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以使用
const map: Dictionary<number> = {} // if you want to store number....
Run Code Online (Sandbox Code Playgroud)
哪个更容易阅读。
| 归档时间: |
|
| 查看次数: |
30465 次 |
| 最近记录: |