ember-cli-typescript icon indicating copy to clipboard operation
ember-cli-typescript copied to clipboard

Enumerable types causing grief

Open lolmaus opened this issue 5 years ago • 3 comments

Which package(s) does this problem pertain to?

  • [x] @types/ember__array

Description

Some of Ember's Enumerable methods are causing typing issues.

  1. Some are typed incorrectly. E. g. .compact() is typed to return NativeArray<T>. If T is Foo | undefined, the result will be NativeArray<Foo | undefined>, even though .compact() explicitly removes undefineds.
  2. TypeScript cannot infer types from some them. mapBy() is typed to return any[], so after .mapBy() not types are checked anymore! You can do all kinds of typing errors downstream, and TypeScript will not warn you.

I don't know if only these two are affected, or there are more. Thus, a broad issue title.

I've been using as Foo[] type casting to work around those issues, and it burned me hard when a refactoring was needed.

I ended up making a tough decision of replacing Ember's custom methods with their explicit vanilla equivalents, e. g.:

  • foos.mapBy('bar')foos.map(foo => foo.bar)
  • foos.compact()foos.filter(foo => foo !== undefined)

This affects not only array methods, but also computed property macros. 😔

This in turn made me wonder if I should keep prototype extensions enabled.

PS Note that it's not Enumerable methods that are bad, it's the typings.

lolmaus avatar Apr 23 '20 08:04 lolmaus

Another problem with shorthand methods is that they don't warn you on typos.

E. g. foos.map(foo => foo.typo) will be reported, but foos.mapBy('typo') is always fine.

I wonder if this can be improved?

lolmaus avatar Apr 23 '20 09:04 lolmaus

This seems to resolve it for compact:

compact(): NonNullable<T>[];

I tried adding to DefinitelyTyped but couldn't figure out how to make a failing test case. dtslint won't recognize a problem where TypeScript would say "type Foo | undefined is not compatible with type Foo".

lolmaus avatar Apr 23 '20 14:04 lolmaus

firstObject and lastObject also seem to be typed incorrectly.

lolmaus avatar Apr 26 '20 11:04 lolmaus

Ember's own types do their best here, but there's a reason we deprecated the array prototype extensions. Net, this is no longer an active issue, and folks should stick to the native Array APIs!

chriskrycho avatar Sep 28 '23 23:09 chriskrycho