skip to Main Content

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


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

    type User1  = {
       [key: string]: any;
       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]: any
       name: string;
       age: number;
       address: string;
    };
    
    Login or Signup to reply.
  2. 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 the User1 properties:

    type User1 = {
      name: string;
      age: number;
      address: string;
    };
    
    const user1: User1 = {
      name: "User 1",
      age: 23,
      address: "123 First St",
    };
    
    let checkParameter: keyof User1 = "name";
    console.log(user1[checkParameter]); // User 1
    
    checkParameter = "age";
    console.log(user1[checkParameter]); // 23
    
    checkParameter = "address";
    console.log(user1[checkParameter]); // 123 First St
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search