Declare Read-Only Tuple Types in TypeScript

Marius Schulz
InstructorMarius Schulz

Share this video with your friends

Send Tweet
Published a year ago
Updated a year ago

Similar to how we can declare read-only array types, we can declare read-only tuple types using the readonly modifier. Any attempt to mutate a value of a read-only tuple type will result in a type error.

Additional Reading

Instructor: [0:00] Similar to how TypeScript supports read-only array types, it also supports read-only tuple types. Here, we have a generic function called swap(). It defines two type parameters, t and u, and it accepts a single tuple with two elements of type t and u. The returned value is a new tuple in which we've swapped the first and second element.

[0:23] Let's go ahead and use our swap function. Let's say that we have a key-value pair where the key is the number 1 and the value is the string "One." Now, we want to turn that into a value-key pair where we swap the two values. We're going to call swap and pass it our key-value pair.

[0:44] As you can see, we're getting a TypeError. TypeScript is saying that the argument of type string or number array is not assignable to parameter of type string or number string or number tuple. This is because we've made a mistake here.

[0:57] If we hover over key-value pair, you can see that TypeScript has inferred key-value pair to be of type array of string or number. This was not what we wanted. What we wanted was a tuple type where the first element is a number and the second element is a string.

[1:14] Now, our code type-checks correctly. If we hover over value-key pair, we can see that we get a tuple in reverse, where now the first element is a string and the second one is a number. All right. Now that our code is type-checking, let's verify that it actually works.

[1:32] I'm going to log our key-value pair to the console as well as our value-key pair. Let's compile the project again and run the file. As we can see, we get two tuples, our original tuple and the swapped one.

[1:50] Just like before, let's go ahead and let's use a read-only tuple type here. Just like before, TypeScript is giving us a TypeError. Again, it's telling us that our read-only tuple type is not assignable to the parameter tuple type because the parameter tuple type is considered to be mutable.

[2:08] We can fix our code by going up here again and making our function accept a read-only tuple. Now, as you can see, all the TypeErrors go away.

[2:18] If you're writing a function that accepts arrays or tuples, consider adding the read-only modifier to these array and tuple types. That way, your function can be used with mutable arrays and tuples as well as read-only arrays and tuples.