DEV Community

Luiz Américo
Luiz Américo

Posted on

TIL: How to reference the item type of an array type?

I have one array type and needed to use the type of its item

Directly from AI (Sonnet 3.7)

In TypeScript, you can reference the type of an item in an array type in several ways:

Method 1: Use indexed access type

type Messages = {
  date: Date;
  content: string;
  userId: string;
  userName: string;
}[]

type MessageItem = Messages[number];
Enter fullscreen mode Exit fullscreen mode

The number index accesses the type of elements in the array.

Method 2: Define the item type separately first

type MessageItem = {
  date: Date;
  content: string;
  userId: string;
  userName: string;
};

type Messages = MessageItem[];
Enter fullscreen mode Exit fullscreen mode

This approach is often clearer, especially if you need to reuse the item type elsewhere in your code.

Method 3: Use ArrayType<T> utility type (custom)

You can also create a utility type if you need to do this frequently:

type ArrayItem<T> = T extends Array<infer U> ? U : never;

type Messages = {
  date: Date;
  content: string;
  userId: string;
  userName: string;
}[]

type MessageItem = ArrayItem<Messages>;
Enter fullscreen mode Exit fullscreen mode

The first method (Messages[number]) is the most direct and commonly used approach to extract the item type from an array type.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Image of DataStax

AI Agents Made Easy with Langflow

Connect models, vector stores, memory and other AI building blocks with the click of a button to build and deploy AI-powered agents.

Get started for free

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay