使用字符串键访问Firestore映射值时IDE提示该字符串未被读取
问题原因与解决方案
你遇到的IDE提示是因为代码里的变量someKey确实没被实际使用——你用点语法theMapInQuestion.someKey访问的是对象名为someKey的字面量属性,而不是变量someKey存储的字符串值作为键。
解决方法:使用方括号语法访问动态键
把点语法改成方括号语法,这样才会引用变量someKey的值来获取映射对应的键:
exports.someFunction = functions.https.onCall(async (data, _context) => { const uid = data.uid; const someKey = data.someKey; // function argument; guaranteed to be a string const settingsDoc = await admin.firestore().doc("settings/" + uid).get(); const theMapInQuestion = settingsDoc.get("theMapInQuestion"); // guaranteed to be a Firestore map of type [string: boolean] // 改用方括号语法,引用someKey变量的值 const theBooleanInQuestion = theMapInQuestion[someKey]; if (theBooleanInQuestion === true) { // proceed } else { ... } });
额外说明
如果你的代码用了TypeScript,可能还需要给theMapInQuestion添加明确的类型定义,确保TypeScript能识别它是字符串索引的布尔值映射,避免类型报错:
const theMapInQuestion = settingsDoc.get("theMapInQuestion") as Record<string, boolean>;
内容的提问来源于stack exchange,提问作者lurning too koad
相关产品推荐
相关产品推荐

