Home > Mobile >  typescript option for iterator and spread operator
typescript option for iterator and spread operator

Time:12-12

I would like to call the iterator of the type below

type datetimeT = { [key: number]: string };

If a create an object this way

let example: dateTimeT = {1: 'A', 2: 'B'};

The spread operator ...example is not recognized because the type doesn't have [Symbol.iterator]() method

My ts option are

  "target": "es6",
  "module": "esnext",
  "lib": [
    "dom",
    "dom.iterable",
    "esnext",
    "es2017"
  ]

What must I do?

CodePudding user response:

Objects are not automatically iterable in Javascript, it has nothing to do with your TSConfig. Every type that you want to be iterable must implement an iterator method:

type MyIterType = {
  [key: number]: string
} & Iterable<string>

const foo: MyIterType = {
  0: 'a',
  1: 'b',
  *[Symbol.iterator] () {
    const values = Object.values(this)
    while (values.length) {
      yield values.pop()
    }
  }
}

const arr = [...foo] // ['b', 'a']

Playground link

  • Related