1

I'm trying to create an object, that works like an array and could have some properties that could iterate the same array:

interface ICustomer {
  orderId: string
  name: string
}

interface ICustomers {
  [key: number]: ICustomer
  findByOrderId: (id:string) => ICustomer
}

Now trying to create an example instance of ICustomers:

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

It shows the following error: Type 'ICustomers' must have a '[Symbol.iterator]()' method that returns an iterator.(2488)

How to implement 'Symbol.iterator' in this case? Maybe there is another approach?

Here is a demo

1 Answer 1

1

Error

In order to use for of you need to provide [Symbol.iterator]

Fix

Add that to the interface and the implementation. Code without any errors:

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.