Generic Arrays
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 60 of 73.
Arrays and generics work together beautifully in TypeScript. When you learned about typed arrays earlier, you used the T[] syntax to specify that an array can only contain elements of a specific type. Generics give you another way to express this same concept.
TypeScript provides an alternative syntax for typed arrays using the Array<T> format:
// These two declarations are equivalent:
let numbers1: number[] = [1, 2, 3];
let numbers2: Array<number> = [1, 2, 3];The Array<T> syntax is particularly useful when working with generic functions that operate on arrays. It makes the generic nature of your code more explicit and readable, especially when you're creating functions that can work with arrays of any type while preserving type safety.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate a generic function named getFirstElement that takes an array of any type and returns the first element or undefined if the array is empty.
The function should:
- Use a generic type parameter
T - Accept one parameter named
arrof typeArray<T> - Return the first element of type
Torundefined - Have an explicit return type annotation of
T | undefined
Create the following arrays using the Array<T> syntax:
stringArrayof typeArray<string>containing["apple", "banana", "cherry"]numberArrayof typeArray<number>containing[10, 20, 30, 40]booleanArrayof typeArray<boolean>containing[true, false, true]emptyStringArrayof typeArray<string>that is empty
Test your function and print the following outputs:
- Print the result of calling
getFirstElementwithstringArray - Print the result of calling
getFirstElementwithnumberArray - Print the result of calling
getFirstElementwithbooleanArray - Print the result of calling
getFirstElementwithemptyStringArray - Print the result of calling
getFirstElementwith a newArray<string>containing["single"]
Cheat sheet
TypeScript provides two equivalent syntaxes for typed arrays:
// These two declarations are equivalent:
let numbers1: number[] = [1, 2, 3];
let numbers2: Array<number> = [1, 2, 3];The Array<T> syntax is particularly useful when working with generic functions that operate on arrays, making the generic nature of your code more explicit and readable while preserving type safety.
Try it yourself
// TODO: Write your code here
// Create the generic function getFirstElement
// Create the required arrays using Array<T> syntax
// Test the function and print the resultsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples6Typing Objects and Interfaces
Inline Object Type AnnotationsType Aliases for ObjectsIntroduction to InterfacesInterfaces vs. Type AliasesOptional & Readonly PropsExtending Interfaces and TypesAdding Methods to InterfacesRecap: Defining Object Shapes9Generics: A First Look
The Problem Generics SolveCreating Generic Identity FuncUsing a Generic FunctionGeneric ArraysGeneric InterfacesRecap: Generic Function Prac