Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How ot fix funciton according TS?

Here is a funciton:

function factoryTableView(category: number) {
    const views =  {
      1: new ImportExportTable()
    };

        return views[category];
}

I got this error message:

Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{ 1: ImportExportTable; }'.
  No index signature with a parameter of type 'number' was found on type '{ 1: ImportExportTable; }'.

How to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Objects implicitly have strings for their properties unless you specify otherwise.

Explicitly define a type for views if you want to use numbers for the property names.

function factoryTableView(category: number) {
    const views: Record<number, ImportExportTable> = {
        1: new ImportExportTable()
    };
    return views[category];
}

(They will still be strings in JS, but TypeScript will require that you use numbers to access them and they will be converted to strings only at runtime).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading