-
-
Notifications
You must be signed in to change notification settings - Fork 571
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Expose ArrayElement
type
#914
base: main
Are you sure you want to change the base?
Expose ArrayElement
type
#914
Conversation
export type ArrayElement<ArrayType extends readonly unknown[]> = | ||
ArrayType extends ReadonlyArray<infer ElementType> | ||
? ElementType | ||
: never; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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'] | null I agree that |
Closes #118
Related: #676. (maybe closes?)
Exposes internal
ArrayElement
type: