typescript - 在类型 ' 上找不到参数类型为 'string' 的索引签名

标签 typescript

我正在研究我的第一个 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/

    相关文章:

    Reactjs,Typescript - 子组件上不存在属性

    angular - 当其中之一具有异步管道时,如何在两个条件下实现 和 ngif

    typescript - 使用 SystemJS 和 TypeScript 从捆绑文件中执行模块

    typescript - 基于条件类型的可选参数

    javascript - 如何衡量 promise 的执行时间?

    JavaScript 音频在使用同一音频对象时多次播放

    reactjs - 无法在 typescript 中的 constructor() 内部调用 super()

    typescript - 在 Babel 7 Standalone 中使用 typescript

    typescript - 在 TypeScript 中扩展参数化接口(interface)的通用接口(interface)

    typescript - 类型错误 : Cannot read property 'Symbol(Symbol.iterator)' of undefined