Home > other >  react and typescript - no index signature with a parameter of type 'string' was found on t
react and typescript - no index signature with a parameter of type 'string' was found on t

Time:03-05

I have an react aplication with typescript, I'm trying to access a property from my component state by key value, but I'm getting the erro below:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Product'.
No index signature with a parameter of type 'string' was found on type 'Product'.

I have a separated types files:

>>> types.ts

export type Product = {
   name: string,
   active: boolean,
   ...
}

And the code of my component I'm trying to access like:

MyComponent.tsx

const [products, setProducts] = useState<Product | null>();

...

const myProduct = 'name';

products[myProduct] // this line will give my editor the warning

products['name'] // this line is fine

Both lines works just fine without any errors on my aplication, but vscode keeps complaning.

CodePudding user response:

The products state can be null according to your useState type, so you should handle that case:

const [products, setProducts] = useState<Product | null>(null);

You can use optional chaining to get undefined is products is null:

products?.[myProduct]

products?.['name']

IF you're trying to render a non existing product, you can return null to bail out of the component, before trying to access non existing properties:

if(!products) return null;

const myProduct = 'name';

products[myProduct]

CodePudding user response:

The error means that defining a variable like const myProduct = 'xxx'; will use the most broad type, which is a string. Depending on the TS version you can use a as const assertion to tell the typescript compiler that the value will never change, so the compiler will take the most narrow type: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions

This should work

const myProduct = 'name' as const;
products[myProduct]
  • Related