Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 表达式类型';字符串';不能用作索引类型_Javascript_Arrays_Typescript - Fatal编程技术网

Javascript 表达式类型';字符串';不能用作索引类型

Javascript 表达式类型';字符串';不能用作索引类型,javascript,arrays,typescript,Javascript,Arrays,Typescript,我开始学习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 }; f

我开始学习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);
  });
}

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

接口对象{
名称:string,
城市:字符串,
年龄:数字,,
}
康斯特约翰={
姓名:“约翰”,
城市:“伦敦”,
年龄:24
};
康斯特·杰里={
姓名:“杰瑞”,
城市:“罗马”,
年龄:43
};
函数filterPerson(arr:Array,term:string,key:keyof iobject):数组{
返回arr.filter(函数(人员:IObject){
const pers=人[钥匙];
如果(pers的类型==“字符串”){
返回匹配(期限);
}
否则{
返回false;
}
});
}
const results=filterPerson([john,jerry],“伦敦”,“城市”);

控制台日志(结果)我认为,这应该可以解决您的问题:

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

请参阅:不要使用
字符串
数字
;使用
string
number
而不是@jcalz的可能副本完全同意不要使用
string
,但更深层次的问题是
key
应该是t
keyof或其过滤版本,以允许
person[key]
access@TitianCernicova-德拉戈米尔·苏尔;最终,他们会发现,
的类型应该是
“name”|“city”
,而不是
IObject的键
,而不是
string
。不确定要在这里走多远。@jcalz不确定我是否理解,当我在person[key]上将字符串更新为字符串时,我得到错误:元素隐式具有“any”类型,因为类型“String”的表达式不能用于索引类型“IObjct”。在类型“IObjct”.ts(7053)上未找到具有“string”类型参数的索引签名。
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);
    });
}