类型字符串上不存在属性id

时间:2016-12-21 18:47:30

标签: typescript

我在IDE中遇到以下错误:UIButtonDoor3这段代码:

func openSecondChoice(whatDoorIsClickedOn: Int) {
    let imageName = whatDoorIsClickedOn == doorWithNumber ? "doorWithMoney" : "doorWithGoat"
    uiButtonDoors[whatDoorIsClickedOn - 1].setBackgroundImage(UIImage(named: imageName), for: UIControlState.normal)
}

完整代码:

<ListView ...>
  <x:Arguments>
    <ListViewCachingStrategy>RecycleElement</ListViewCachingStrategy>
  </x:Arguments>
</ListView>

这是我的假设,因为我将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 "";
}

1 个答案:

答案 0 :(得分:11)

您必须将您的属性包装在对象中:

function createCustomer(name: string, id: number, age: number, city: string) {
        customer.push({ name, id, age, city });
}

其中{ name, id, age, city }是ES2015等同于:

{
    id: id,
    name: name,
    age: age,
    city: city
}

为了避免这种错误,我倾向于创建强制结构的界面:

interface ICustomer {
    id: number;
    name: string;
    age: number;
    city: string;
}

您分配给您的数组:

let customer: ICustomer[];

除了更好的类型检查外,它还为您提供了更好的语法提示。

编辑: 我已经审核了您的代码,并对实践提出了一些建议:

  • 始终将返回类型提供给函数
  • 尝试不对函数内部的外部变量进行处理,如果需要将它们作为参数传递
  • 不要将函数定义与实际代码混合

代码价值超过1000字。这是重构版本:

const allCustomers: ICustomer[] = customers();

interface ICustomer {
    id: number;
    name: string;
    age: number;
    city: string;
}

function customers(): ICustomer[] {
    let id: number = 0;

    return [
        createCustomer(id++, "Drew", 22, "Glassboro"),
        createCustomer(id++, "Mike", 40, "Rineyville"),
        createCustomer(id++, "Justin", 19, "Jonesboro"),
        createCustomer(id++, "Alex", 15, "Paulsboro"),
        createCustomer(id++, "Phil", 32, "Glassboro")
    ];
}

function createCustomer(id: number, name: string, age: number, city: string): ICustomer {
    return { id, name, age, city };
}

function getCustomerInformation(customers: ICustomer[], id: number): ICustomer {
    // Note undefined is returned if object not found
    return customers.find(customer => customer.id === id);
}