我正在研究我的第一个 firebase typescript 函数项目
我有以下代码片段。
const files = {
status: './src/api/status.f.js',
invite: './src/api/invite.f.js',
user: './src/api/user.f.js',
auth: './src/api/auth.f.js',
social: './src/api/social.f.js'
}
for (let file in files)
if (files.hasOwnProperty(file)) {
// Setting function name equivalent to the file name
if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === file) {
const ApiClass = require(files[file])
const app = new ApiClass(context)
exports[file] = app.handler
}
}
在这一行中,我收到以下错误
const ApiClass = require(files[file])
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ status: string; invite: string; user: string; auth: string; social: string; }'. No index signature with a parameter of type 'string' was found on type '{ status: string; invite: string; user: string; auth: string; social: string; }'
主要问题:有人可以帮我弄清楚我在这里做错了什么吗?
最佳答案
显示类型错误是因为您打开了 "noImplicitAny": true
在 tsconfig 中。
如果您想保留"noImplicitAny": true
,那么您的问题有 2 个修复程序,请选择其中一个。
const ApiClass = require(files[file as keyof typeof files])
const files: { [key: string]: string } = { ... }
经过一番挖掘,我认为最好的方法是增加
Object.prototype.hasOwnProperty()
方法的签名。// somewhere in your project, write:
interface Object {
hasOwnProperty<T>(this: T, v: any): v is keyof T
}
这样.hasOwnProperty
充当类型保护器,缩小 file
的类型成为 keyof typeof files
自动地。
关于typescript - 在类型 ' 上找不到参数类型为 'string' 的索引签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58811860/