Generic Array First Element
Write a generic TypeScript function that returns the first element of an array. Use the generic type parameter T to capture the array element type. The function should accept items: T[] and return T | undefined (undefined for empty arrays).
This is a classic example of TypeScript generics: the function signature function first<T>(items: T[]): T | undefined preserves the element type through the generic parameter T. If the array is empty, return undefined.
TypeScript generics allow the function to work with arrays of any type while maintaining type safety. The caller gets back the correct type without needing type assertions.
Generics in TypeScript allow functions to work with any type while preserving type information. The <T> syntax declares a type parameter that can be used throughout the function signature. The return type T | undefined uses a union type to handle both the success and failure cases.
This pattern is commonly used in TypeScript libraries to provide type-safe access to array elements, object properties, and API responses.
TypeScript generics enable reusable, type-safe utility functions. The function signature firstItem<T>(items: T[]): T | undefined documents that the return type matches the array element type. This prevents type errors when using the result downstream.
Compared to using any, generics preserve the connection between input and output types, catching mismatches at compile time rather than runtime.
Example Input & Output
Algorithm Flow

Solution Approach
Best Answers
function firstItem(items: any[]): any {
if (items.length === 0) return undefined;
return items[0];
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
