Skip to content

Instantly share code, notes, and snippets.

@thebuilder
Created July 20, 2022 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebuilder/b22edc9882b5208d27a6719f08309eca to your computer and use it in GitHub Desktop.
Save thebuilder/b22edc9882b5208d27a6719f08309eca to your computer and use it in GitHub Desktop.
TypeScript: Pick type of item in an Array
/**
* Get an element from an array
* @example
* interface Item {
* id: number
* }
*
* interface BunchOfItems extends Array<Item> {}
*
* interface SingleItemAgain extends ArrayElement<BunchOfItems> {}
*
* // You can use it again as a single item
* const test: SingleItemAgain = {
* id: 123
* }
*/
type ArrayElement<Type> = Type extends Array<infer Item> ? Item : Type;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment