Skip to main content

Array and Tuples

ลองอ่านเว็บนี้ Type Level TypeScript / Arrays & Tuples มาก่อนแล้วจะเข้าใจมากขึ้น

Basic Tuples

Extracting type from indices of a tuple

type TupleMember = ["Thada", 30];

type Name = TupleMember[0]; // "Thada"
type Age = TupleMember[1]; // 30

Extracting type from several indices

type TupleMember = ["Thada", 30, true];

type NameOrAge = TupleMember[0 | 1]; // "Thada" | 30

Extracting type from tuples

type TupleMember = ["Thada", 30, true];

type TupleElementType = TupleMember[number]; // "Thada" | 30 | true

Concat Tuples

type Tuple1 = [4, 5];
type Tuple2 = [1, 2, 3, ...Tuple1]; // => [1, 2, 3, 4, 5]

Basic Arrays

type Names = string[];

type Users = Array<string>; // same as `string[]`

type UnionArray = (string | number)[]; // Accept arrays of string or number

Extracting the type in an Array

type Names = string[];
type ContentType = Names[number]; // string

Getting Prepare to More Advance Type

Tail of Array always be array

type CheckTailStatus<T extends any[]> = T extends [infer Head, ...infer Tail]
? Tail extends any[]
? 'Tail is an array'
: 'Tail is not an array'
: 'Empty array';

// Test Assertion
import type { Equal, Expect, ExpectFalse } from '@type-challenges/utils'
type cases = [
Expect<Equal<'Empty array', CheckTailStatus<[]>>>,
Expect<Equal<'Tail is an array', CheckTailStatus<['cat']>>>,
Expect<Equal<'Tail is an array', CheckTailStatus<['cat', 'dog']>>>,
ExpectFalse<Equal<'Tail is not an array', CheckTailStatus<['cat']>>>
];

playground

Loop in Array (Using Recursive)

Recursive Array

type RecursiveArray<T> = T extends [infer Head, ...infer Tail]
? [Head, ...RecursiveArray<Tail>]
: [];

// Test Assertion
import type { Equal, Expect, ExpectFalse } from '@type-challenges/utils'
type cases = [
Expect<Equal<RecursiveArray<[1, 2, 3]>, [1, 2, 3]>>,
Expect<Equal<RecursiveArray<"cat">, []>>,
Expect<Equal<RecursiveArray<1>, []>>,
ExpectFalse<Equal<RecursiveArray<[1]>, []>>,
]

playground

Reverse Array

type ReverseArray<T> = T extends [infer Head, ...infer Tail]
? [...ReverseArray<Tail>, Head]
: [];

// Test Assertion
import type { Equal, Expect, ExpectFalse } from '@type-challenges/utils'
type cases = [
Expect<Equal<ReverseArray<[1, 2, 3]>, [3, 2, 1]>>,
Expect<Equal<ReverseArray<"cat">, []>>,
Expect<Equal<ReverseArray<1>, []>>,
ExpectFalse<Equal<ReverseArray<[1]>, []>>,
]

playground

Read More