We can declare a typed tuple in TypeScript, for example, with the type annotation [string, number]
. This means an array of 2 elements where the first element needs to be a string and the second a number.
We can also declare read-only arrays with ReadonlyArray<string>
which means a read-only array of strings.
Now I want to have a read-only tuple like in the first example, but I want it to be read-only like in the second example. How would I declare that?
TypeScript lets us define array types as read-only so that we get a type error if we attempt to add, remove, or replace any elements of the array. We can use the readonly keyword to make an array type read-only. Alternatively, we can use the ReadonlyArray<T> type instead of Array<T> or T[] .
You can declare an array of tuple also. var employee: [number, string][]; employee = [[1, "Steve"], [2, "Bill"], [3, "Jeff"]]; TypeScript generates an array in JavaScript for the tuple variable. For example, var employee: [number, string] = [1, 'Steve'] will be compiled as var employee = [1, "Steve"] in JavaScript.
An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below. let values: (string | number)[] = ['Apple', 2, 'Orange', 3, 4, 'Banana']; // or let values: Array<string | number> = ['Apple', 2, 'Orange', 3, 4, 'Banana'];
The structure of the tuple needs to stay the same (a string followed by a number), whereas the array can have any combination of the two types specified (this can be extended to as many types as is required).
Since the type [string, number]
already is an Array
, you can simply use:
Readonly<[string, number]>
Example:
let tuple: Readonly<[string, number]> = ['text', 3, 4, 'another text']; tuple[0] = 'new text'; //Error (Readonly) let string1: string = tuple[0]; //OK! let string2: string = tuple[1]; //Error (Type number) let number1: number = tuple[0]; //Error (Type string) let number2: number = tuple[1]; //OK! let number3: number = tuple[2]; //Error (Type any)
With so-called const contexts, the compiler can be told to treat an array or an object as immutable, meaning that their properties are read-only. This also allows the creation of literal tuple types with narrower type inference (i.e. your ["a", "b"]
can for the first time be of type ["a", "b"]
, not string[]
without specifiying the whole thing as a contextual type)
The syntax will look like this:
let foo = ["text", 1] as const
or
let foo = <const> ["text", 1]
Here is the extended information of the corresponding PR.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With