Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No index signature with a parameter of type 'string' was found on type '

Tags:

typescript

I was working on my first firebase typescript function project

I have following code snippet.

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
        }
    }

In this, at this line i am getting following error 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; }'

Primary Question: Can someone help me figure out what I am doing wrong here?

like image 705
anny123 Avatar asked Nov 12 '19 04:11

anny123


People also ask

Is not assignable to type string?

The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.

Is not assignable to type never []'?

The error "Argument of type is not assignable to parameter of type 'never'" occurs when we declare an empty array without explicitly typing it and attempt to add elements to it. To solve the error, explicitly type the empty array, e.g. const arr: string[] = []; .


1 Answers

The type error is shown because you turned on "noImplicitAny": true in tsconfig.

If you like to keep "noImplicitAny": true, then there're 2 fixes to your problem, choose either one.

  1. const ApiClass = require(files[file as keyof typeof files])
  2. const files: { [key: string]: string } = { ... }

After some digging, I think the optimal way is to augment the Object.prototype.hasOwnProperty() method's signature.

// somewhere in your project, write:

interface Object {
  hasOwnProperty<T>(this: T, v: any): v is keyof T
}

This way .hasOwnProperty acts as a type guard that narrows down type of file to be keyof typeof files automatically.

like image 118
hackape Avatar answered Sep 27 '22 17:09

hackape