5

I overrode Object.entries like this:

interface ObjectConstructor {
  entries<T extends Record<string, any>>(o: T): {
      [K in keyof T]: [K, T[K]];
  }[keyof T][];
}

It usually works fine. However, in some cases, I'm getting:

Type '["alignContent", AlignContent | undefined] | ["alignItems", AlignItems | undefined] | ["alignSelf", AlignSelf | undefined] | ... 781 more ... | undefined' must have a '[Symbol.iterator]()' method that returns an iterator.

The last type in the union is undefined, making it unable for me to destructure like this:

const style: Partial<React.CSSProperties> = {
  height: '123px',
};
for (const [k, v] of Object.entries(style)) {
  ...
}

According to the type definition, it should never return undefined. Why is it returning undefined? I guess it's safe to just omit undefined.

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284

1 Answers1

2

Your example for the style property is not representative of your real usage. The code supplied works just fine on it's own in both typescript 3.9 and 4.1 (with React 16.x and 17.x).

To answer your question:

According to the type definition, it should never return undefined. Why is it returning undefined? I guess it's safe to just omit undefined.

So yes, it's safe to do this, if you cannot solve the data you are using being messy.

Your code should look something like this (although there is more than 1 way to accomplish this)

interface ObjectConstructor {
  entries<T extends Record<string, any>>(o: T): {
    [K in keyof Omit<T, undefined>]: [K, T[K]];
  }[keyof Omit<T, undefined>][];
}
Kevin Sijbers
  • 814
  • 7
  • 19