adplus-dvertising

Expression Type 'String' cannot be used as an index type

Asked 3 years ago
Viewed 563 times

I started learning typescript, so I'm creating situations to resolve, I'm getting error not sure why, see code above:

interface IObjct {
  name: string,
  city: string,
  age: number,
}


const john = {
  name: "John",
  city: "London",
  age: 24
};

const jerry = {
 name: "Jerry",
 city: "Rome",
 age: 43
};

function filterPerson(arr: Array<IObjct>, term: string, key: string) {
  return arr.filter(function(person) {
    return person[key].match(term);
  });
}

I'm getting error on line : return person[key].match(term);

person[key]

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IObjct'.

No index signature with a parameter of type 'string' was found on type 'IObjct'.ts(7053)

filterPerson([john, jerry], "London", "city");

asked 3 years ago

Correct Answer

I think, this should solve your problem:

interface IObjct {
    name: string;
    city: string;
    age: number;
}


const john = {
    name: "John",
    city: "London",
    age: 24,
};

const jerry = {
    name: "Jerry",
    city: "Rome",
    age: 43,
};

function filterPerson(arr: IObjct[], term: string, key: string) {
    return arr.filter(function (person) {
        return person[key].match(term);
    });
}
answered 3 years ago

Other Answer

You may do something like below to check for the types:

interface IObjct {
  name: string,
  city: string,
  age: number,
 
}


const john = {
  name: "John",
  city: "London",
  age: 24
};

const jerry = {
 name: "Jerry",
 city: "Rome",
 age: 43
};

function filterPerson(arr: Array<IObjct>, term: string, key: keyof IObjct):Array<IObjct> {
  return arr.filter(function (person: IObjct) {
    const pers = person[key];
    if (typeof pers === "string") {
      return pers.match(term);
    }
    else {
      return false;
   }
  });
}

const results = filterPerson([john, jerry], "London", "city");
console.log(results);
answered 3 years ago