Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element implicitly has an 'any' type. No index signature with a parameter of type 'string' was found on type 'User1'

I tried using computed properties in TypeScript, but I'm getting the following error:

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

Code:

type User1 = {
  name: string;
  age: number;
  address: string;
};

const user1: User1 = {
  name: "user1",
  age: 23,
  address: "address",
};

let checkParameter: string | number = "name";
console.log(user1[checkParameter]); //error occurring here

checkParameter = "age";
console.log(user1[checkParameter]); //error occurring here

checkParameter = "address";
console.log(user1[checkParameter]); //error occurring here

The checkParameter is random and will be decided at runtime.

I'm expecting error free execution.

like image 340
Arun Muralidharan Avatar asked Oct 15 '25 00:10

Arun Muralidharan


1 Answers

You can add [key: string]: string to specify that the type User1 has properties with keys of type string

type User1  = {
   [key: string]: string;
   name: string;
   age: number;
   address: string;
};

const user1: User1 = {
   name: "user1",
   age: 23,
   address: "address",
};

let checkParameter: string | number = "name";
console.log(user1[checkParameter]);

Since checkParameter has two types string | number and it refers to a key, if the User1 type will have a key of type number, add this type to the key:

type User1  = {
   [key: string | number]: string
   name: string;
   age: number;
   address: string;
};
like image 131
Santiago Avatar answered Oct 17 '25 15:10

Santiago



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!