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.

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay