Conversation
| export type ArrayElement<ArrayType extends readonly unknown[]> = | ||
| ArrayType extends ReadonlyArray<infer ElementType> | ||
| ? ElementType | ||
| : never; |
There was a problem hiding this comment.
I'm not sure this works @strongpauly
Should this be more?:
type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[] ? ElementType : never;Copy paste from stackoverflow.com/questions/41253310/typescript-retrieve-element-type-information-from-array-type
There was a problem hiding this comment.
Well, as long as it returns a union of the types of the array elements, its fit for purpose, IMO.
|
Isn't this type already covered by https://github.com/sindresorhus/type-fest/blob/main/source/iterable-element.d.ts ? |
Hm, I'd assume so, but the tests for
|
|
Any update here? |
|
Is it really worth to import and use a custom type instead of just using a literal type offered by TypeScript? - array[number]
+ ArrayElement<array>The examples and tests don’t show why this would be beneficial. |
It's more of a syntactic and aesthetic improvement than a functional one. I do think it is a bit more verbose, but the type offered by TS can be hard to read/interpret at first glance: type MyType = MyComplexType['property_1'][number]['subprop_1'] | null
// vs
type MyType = ArrayElement<MyComplexType['property_1']>['subprop_1'] | null |
|
In your example it does not look like an advantage, it's hard to follow and does not match the order of the JS code. 0 1 2 3
complexObject .property_1 [0] .subprop_1
0 1 2 3
type MyType = MyComplexType['property_1'][number]['subprop_1'] | null
// vs
2 0 1 3
type MyType = ArrayElement<MyComplexType['property_1']>['subprop_1'] | nullI agree that |
eabb987 to
cc2b0f2
Compare

Closes #118
Related: #676. (maybe closes?)
Exposes internal
ArrayElementtype: