0
votes

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");
2
See the FAQ entry: don't use String or Number; use string and number insteadjcalz
@jcalz fully agree with don't use String but the deeper issue is that key should probbaly be a keyof T or a filtered version of that to allow the person[key] accessTitian Cernicova-Dragomir
@TitianCernicova-Dragomir sure; ultimately they will find that key should be of type "name" | "city" and not keyof IObjct and not string and not String. Not sure how far down the rabbit hole to go here.jcalz
@jcalz not sure I understood, when I update String to string, on person[key], I get error: 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).bernlt

2 Answers

0
votes

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);
    });
}
-1
votes

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);