ember-cli-typescript
ember-cli-typescript copied to clipboard
Enumerable types causing grief
Which package(s) does this problem pertain to?
- [x] @types/ember__array
Description
Some of Ember's Enumerable methods are causing typing issues.
- Some are typed incorrectly. E. g.
.compact()is typed to returnNativeArray<T>. IfTisFoo | undefined, the result will beNativeArray<Foo | undefined>, even though.compact()explicitly removesundefineds. - TypeScript cannot infer types from some them.
mapBy()is typed to returnany[], 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.
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?
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".
firstObject and lastObject also seem to be typed incorrectly.
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!