Lesson 02-TypeScript Advanced Features

Arrays

Array Type Declarations

Arrays can be typed in two ways:

  • First Way: Add square brackets after the type of the array elements.
let arr: number[] = [1, 2, 3];
let arr: (number | string)[];
  • Second Way: Use TypeScript’s built-in Array interface.
let arr: Array<number | string>;

Array Type Inference

// Inferred as any[]
const arr = [];
// Inferred as number[]
arr.push(123);
// Inferred as (string | number)[]
arr.push('abc');

// Inferred as number[]
const arr = [123];
arr.push('abc'); // Error

Read-Only Arrays and const Assertions

// Arrays declared with `const` can have their elements modified.
const arr = [0, 1];
arr[0] = 2;

// Read-only array
const arr: readonly number[] = [0, 1];
arr[1] = 2; // Error
arr.push(3); // Error
delete arr[0]; // Error

let a1: number[] = [0, 1];
let a2: readonly number[] = a1; // Valid
a1 = a2; // Error

// Error
const arr: readonly Array<number> = [0, 1];

// TypeScript provides two generics for read-only arrays.
const a1: ReadonlyArray<number> = [0, 1];
const a2: Readonly<number[]> = [0, 1];

Multi-Dimensional Arrays

TypeScript uses T[][] to represent two-dimensional arrays, where T is the type of the innermost array elements.

var multi: number[][] = [[1, 2, 3], [23, 24, 25]];

Tuples

Tuples require explicit type declarations for each element. TypeScript distinguishes tuples from arrays by the placement of type annotations: types inside square brackets ([number]) indicate a tuple, while types outside (number[]) indicate an array.

let a: [number] = [1]; // Tuple
const s: [string, string, boolean] = ['a', 'b', true]; // Tuple
let a: number[] = [1]; // Array

let a: [number, number?] = [1]; // Optional tuple members can use the `?` suffix.

Optional elements (?) must appear at the end of the tuple, after all required members.

type myTuple = [number, number, number?, string?];

let x: [string, string] = ['a', 'b'];
x[2] = 'c'; // Error: Out-of-bounds access

// Spread operator in tuples can be used anywhere but must be followed by an array or tuple.
type t1 = [string, number, ...boolean[]];
type t2 = [string, ...boolean[], number];
type t3 = [...boolean[], string, number];

type Tuple = [...any[]];
type Tuple = [string, number];
type Age = Tuple[1]; // number

const arr: [number, number] = [1, 2];
function add(x: number, y: number) {
  // ...
}
add(...arr); // Valid

const arr = [1, 2] as const; // Const assertion

Read-Only Tuples

// Method 1
type t = readonly [number, string];
// Method 2
type t = Readonly<[number, string]>;

Membership Required

You must be a member to access this content.

View Membership Levels

Already a member? Log in here

Share your love