我得到我的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 "";
}
這是因爲我的假設我用any
代替let customer: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'函數返回一串字符串... –
您可能需要'customer.push({name,id,age,city});'您的命名非常非常混亂。並且您從返回類型爲string []的函數返回客戶,該客戶的類型爲any []。這沒有什麼意義。 –