Skip to Content
Language reference

Arrays and strings

Work with growable arrays, fixed native buffers, and UTF-16 indices.

T[] and Array<T> are growable arrays. Assigning an array to another variable gives both variables a reference to the same array. They see the same elements after a push, including when the runtime has to grow the backing buffer.

const samples: int[] = [3, 5]
const alias = samples

samples.push(7)   // returns 3, the new length
alias[2]          // 7

The element type determines which values the array accepts. A dense int[] can keep its elements in primitive storage. The ordinary numeric literal [3, 5] infers number[]. A mixed literal such as ["header", 5, null] preserves the type and value of each element.

Reading an element

For an ordinary array, xs[i] has type T | undefined when the element's presence is unknown. A missing property gives undefined. An element containing null gives null. Use .at(i) to count back from the end with a negative index. Brackets treat -1 as the property name "-1".

const xs = [3, 5]
xs.at(-1)   // 5
xs[-1]      // undefined
xs.at(2)    // undefined
xs[2]       // undefined

With dense primitive storage, xs[i] ?? 0 can use a bounds check and a primitive load without allocating a box. A sparse array must also account for holes.

Fixed buffers

Use FixedArray<T> for a native interface that shares storage of a fixed length. Reading buf[i] returns T for a valid index and throws a bounds error for an invalid one. Indexed writes are visible through every alias. The type excludes operations that change its length.

const indices: FixedArray<int> = [3, 5]
indices[0] = 9

A Java caller can hold the same int[] and read the new first element. Converting a growable array into an independent fixed buffer copies its elements.

Strings and characters

String length, indexing, and slicing use UTF-16 code units. A char holds one code unit, including either half of a surrogate pair. String iteration combines a valid pair into one Unicode code point.

const face = "😀"
face.length                      // 2
face.slice(0, 1).charCodeAt(0)   // 0xD83D

const slash: char = "/"
"src/main.ts".indexOf(slash)     // 3

Equality compares the exact sequence of code units. The strings "\u00E9" and "e\u0301" can look identical and still form two distinct Map keys. These rules apply on both the JVM and Swift targets.

On this page