DEV Community

ccsunny
ccsunny

Posted on

Typescript Arrays

Image description

In TypeScript, arrays are considered to be collections of single, “generic” types of values. All elements must be of the same type of data as prescribed in the array definition.

1. Defining an array

Array types can be inferred during the initialization of a new array.

In this example, the vowels array is inferred to consist of elements of type string:

const vowels = ['a', 'e', 'i', 'o', 'u'];

vowels.push('y'); // Ok

vowels.push(7);
// Error: Argument of type 'number' is not assignable to parameter of type 'string'.
Enter fullscreen mode Exit fullscreen mode

Arrays can also be defined with the “generic” type of its elements already preset in two ways:

const vowels: string[] = ['a', 'e', 'i', 'o', 'u'];

// alternate way using Array class
const altVowels: Array<string> = ['a', 'e', 'i', 'o', 'u'];
Enter fullscreen mode Exit fullscreen mode

2. Array Types

An array type consists of the type of values inside the array followed by square brackets [].

Arrays without any initial contents may be declared as that type to tell TypeScript what will later go into them.

In this example, dates doesn’t initially include a value, so declaring it as Date[] tells TypeScript what’s allowed in it:

const dates: Date[] = [];

dates.push(new Date('2021-12-1994')); // Ok

dates.push(10241995);
// Error: Argument of type 'number' is not assignable to parameter of type 'Date'.

Enter fullscreen mode Exit fullscreen mode

3. Array Methods (Built-in):

TypeScript inherits JavaScript's built-in array methods.
Common methods include:

  • push() - Add element(s) to the end.
  • pop() - Remove and return the last element.
  • shift() - Remove and return the first element.
  • unshift() - Add element(s) to the beginning.
  • concat() - Merge two or more arrays.
  • slice() - Extract a section of an array.
  • map() - Create a new array with transformed elements.
  • filter() - Create a new array with elements passing a test.
  • reduce() - Reduce an array to a single value.
  • Many more! (Refer to JavaScript documentation for details)

4. Generic Arrays

Generics allow creating reusable array types that work with various data types.
Use angle brackets <> to specify the generic type placeholder.

function identity<T>(arr: T[]): T[] {
  return arr;  // Function works with any array type (T)
}

let numbers: number[] = identity([1, 2, 3]);
let colors: string[] = identity(["red", "green"]);

Enter fullscreen mode Exit fullscreen mode

5. Advanced Array Features

Readonly Arrays: Use readonly keyword to create arrays whose elements cannot be changed after initialization.
Tuple Types: Define arrays with specific element types and fixed length at compile time.

let fruits: readonly string[] = ["apple", "banana"];  // Readonly array

let person: [string, number] = ["John", 30];  // Tuple (string, number)
Enter fullscreen mode Exit fullscreen mode

6. Utility Types:

Explore utility types like Partial, Pick, for advanced array manipulation scenarios.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more