我正在研究我的第一个 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
}
}
Run Code Online (Sandbox Code Playgroud)
在这一点上,在这一行我收到以下错误 const ApiClass = require(files[file])
元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 '{ status: string; 邀请:字符串;用户:字符串;身份验证:字符串;社交:字符串;}'。在类型“{ status: string;”上找不到带有“string”类型参数的索引签名。邀请:字符串;用户:字符串;身份验证:字符串;社交:字符串;}'
主要问题:有人可以帮我弄清楚我在这里做错了什么吗?
hac*_*ape 15
显示类型错误是因为您"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
}
Run Code Online (Sandbox Code Playgroud)
这种方式.hasOwnProperty作为一种类型保护,file可以keyof typeof files自动缩小类型的范围。
| 归档时间: |
|
| 查看次数: |
3626 次 |
| 最近记录: |