DEV Community

Cover image for How to make a readonly tuple type in TypeScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to make a readonly tuple type in TypeScript?

Originally posted here!

To make a readonly tuple type, we can use the keyword readonly before the tuple type declaration body in TypeScript.

TL;DR

// a readonly tuple type
type ReadonlyTupleType = readonly [string, number];

// assign the tuple type to an array
const arr: ReadonlyTupleType = ["John Doe", 100];

// add a 3rd element to the array
// ❌ Error.
// Index signature in type 'ReadonlyTupleType' only permits reading.
arr[2] = 1000;
Enter fullscreen mode Exit fullscreen mode

For example, let's make a tuple type called ReadonlyTupleType using the type alias declaration like this,

// a tuple type
type ReadonlyTupleType = [string, number];
Enter fullscreen mode Exit fullscreen mode

As you can see we have made a tuple type where it can contain only 2 array elements where the first element should be a value of string type and the second element should be a value of number type.

Now to make it a readonly tuple type, we can use the readonly keyword before tuple type declaration body like this,

// a readonly tuple type
type ReadonlyTupleType = readonly [string, number];
Enter fullscreen mode Exit fullscreen mode

We have made a readonly tuple type. Now let's assign the tuple type to an array.

It can be done like this,

// a readonly tuple type
type ReadonlyTupleType = readonly [string, number];

// assign the tuple type to an array
const arr: ReadonlyTupleType = ["John Doe", 100];
Enter fullscreen mode Exit fullscreen mode

Now let's also try to add a 3rd element to the readonly array like this,

// a readonly tuple type
type ReadonlyTupleType = readonly [string, number];

// assign the tuple type to an array
const arr: ReadonlyTupleType = ["John Doe", 100];

// add a 3rd element to the array
// ❌ Error.
// Index signature in type 'ReadonlyTupleType' only permits reading.
arr[2] = 1000;
Enter fullscreen mode Exit fullscreen mode

As you can see from the above code the TypeScript is not allowing us to assign the 3rd array element and shows an error saying Index signature in type 'ReadonlyTupleType' only permits reading. which is what we want to happen.

We have successfully made the array into a readonly array using the readonly tuple type in TypeScript.

If you want to know more about what a tuple type is, see the blog on creating tuple types in TypeScript.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)