I tried using computed properties in typescript. But getting below error.
The checkParameter is random & will be decided on runtime.
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 occuring here
checkParameter = "age";
console.log(user1[checkParameter]); //error occuring here
checkParameter = "address";
console.log(user1[checkParameter]); //error occuring here
Im expecting, Error free execution.
2
Answers
You can add
[key: string]: string
to specify that the type User1 has properties with keys of typestring
Since
checkParameter
has two typesstring | number
and it refers to a key, if the User1 type will have a key of type number, add this type to the key:One solution is to change the type for
checkParameter
to a union of the strings representing each property.let checkParameter: name" | "age" | "address" = "name"
Update: As @jcalz suggested,
keyof User1
would dynamically represent theUser1
properties: