表达式类型“字符串”不能用作索引类型

时间:2019-10-28 14:11:42

标签: javascript arrays typescript

我开始学习打字稿,所以我正在创建要解决的情况,但出现错误并不确定原因,请参见上面的代码:

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

我在网上遇到错误:return person [key] .match(term);

person [key]

元素隐式地具有“ any”类型,因为类型“ string”的表达式不能用于索引类型“ IObjct”。

在类型“ IObjct”上未找到带有“字符串”类型参数的索引签名。ts(7053)

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

2 个答案:

答案 0 :(得分:0)

我认为,这应该可以解决您的问题:

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 :(得分:-1)

您可以执行以下操作来检查类型:

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