我在我的IDE中遇到了以下错误,即代码行:Property id does not exist on type string typeScript
if(customer.id === id) {//doesn't like customer.id
return customer;
}
完整代码:
let customer:any [];
function Customers(): string[] {
let id = 0;
createCustomer("Drew",id++,22,"Glassboro");
createCustomer("Mike",id++,40,"Rineyville");
createCustomer("Justin",id++,19,"Jonesboro");
createCustomer("Alex",id++,15,"Paulsboro");
createCustomer("Phil",id++,32,"Glassboro");
return customer;
}
function createCustomer(name:string,id:number,age:number,city:string){
customer.push(name,id,age,city);
}
const allCustomers = Customers();
function getCustomerInformation(id:number): string {
for (let customer of allCustomers) {
if(customer.id === id){
return customer;
}
}
return "";
}
我曾经认为,由于我在 let customer:any [];
中使用了 any
,因此可以在其中放置不同的变量。
----------------- 感谢一些帮助,这是我的新解决方案--------
interface ICustomer{
id: number;
name: string;
age: number
city: string
}
let customers: Array<ICustomer>;
function generateCustomers(): void {
let id: number = 0;
createCustomer("Drew", id++, 22, "Glassboro");
createCustomer("Mike", id++, 40, "Rineyville");
createCustomer("Justin", id++, 19, "Jonesboro");
createCustomer("Alex", id++, 15, "Paulsboro");
createCustomer("Phil", id++, 32, "Glassboro");
}
function getAllCustomers(): ICustomer[]{
generateCustomers();
return customers;
}
function createCustomer(name:string,id:number,age:number,city:string): void {
let newCustomer:ICustomer = {id:id,name:name,age:age,city:city};
customers.push(newCustomer);
}
const allCustomers = getAllCustomers;
function getCustomerInformation(id:number): ICustomer {
for (let customer of allCustomers()) {
if(customer.id === id){
return customer;
}
}
return null;
}
console.log(getCustomerInformation(1));
customers
函数正在返回一个字符串数组... - Diogo Sgrillocustomer.push({name,id,age,city});
。你的命名非常混乱。而且你从一个返回类型为 string[] 的函数中返回了类型为 any[] 的 customer。这没有太多意义。 - JB Nizet