Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.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
如何使用迭代关联数组本身的属性在typescript中创建关联数组_Typescript - Fatal编程技术网

如何使用迭代关联数组本身的属性在typescript中创建关联数组

如何使用迭代关联数组本身的属性在typescript中创建关联数组,typescript,Typescript,我正在尝试创建一个对象,它的工作方式类似于数组,并且可以具有一些可以迭代相同数组的属性: interface ICustomer { orderId: string name: string } interface ICustomers { [key: number]: ICustomer findByOrderId: (id:string) => ICustomer } 现在尝试创建iccustomers的示例实例: const customers: ICustome

我正在尝试创建一个对象,它的工作方式类似于数组,并且可以具有一些可以迭代相同数组的属性:

interface ICustomer {
  orderId: string
  name: string
}

interface ICustomers {
  [key: number]: ICustomer
  findByOrderId: (id:string) => ICustomer
}
现在尝试创建
iccustomers
的示例实例:

const customers: ICustomers = {
  0: {
    orderId: 'aaa',
    name: "Johny"
  },
  1: {
    orderId: 'bbb',
    name: "Pablo"
  },

  findByOrderId: function(id: string) {
    for (customer of this) {
      if (customer.orderId === id) {
        return customer
      }
    }

    return null
  }
}
它显示以下错误:
类型“icCustomers”必须有一个“[Symbol.iterator]”方法,该方法返回迭代器。(2488)

在这种情况下如何实现“Symbol.iterator”?也许还有别的办法

是一个演示错误 要使用的,您需要提供[Symbol.iterator]

修理 将其添加到接口和实现中。无任何错误的代码:

interface ICustomer {
  orderId: string
  name: string
}

interface ICustomers {
  [key: number]: ICustomer
  [Symbol.iterator]: () => Generator<ICustomer>
  findByOrderId: (id: string) => ICustomer | null
}

const customers: ICustomers = {
  0: {
    orderId: 'aaa',
    name: "Johny"
  },
  1: {
    orderId: 'bbb',
    name: "Pablo"
  },

  [Symbol.iterator]: function* () {
    yield this[0];
    yield this[1];
  },

  findByOrderId: function (id: string) {
    for (let customer of this) {
      if (customer.orderId === id) {
        return customer
      }
    }

    return null
  }
}
接口客户{
orderId:字符串
名称:string
}
接口客户{
[关键字:编号]:i客户
[符号.迭代器]:()=>生成器
findByOrderId:(id:string)=>ICCustomer | null
}
客户:ICustomers={
0: {
orderId:'aaa',
姓名:“约翰尼”
},
1: {
orderId:'bbb',
姓名:“巴勃罗”
},
[符号.迭代器]:函数*(){
产生这个[0];
产生这个[1];
},
findByOrderId:函数(id:字符串){
为了(让客户知道){
if(customer.orderId==id){
退货客户
}
}
返回空
}
}