Issue
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?
Solution
From Typescript version 3.4 you can just prefix tuple type with readonly
keyword (source).
TypeScript 3.4 also introduces new support for
readonly
tuples. We can prefix any tuple type with thereadonly
keyword to make it areadonly
tuple, much like we now can with array shorthand syntax. As you might expect, unlike ordinary tuples whose slots could be written to,readonly
tuples only permit reading from those positions.function foo(pair: readonly [string, string]) { console.log(pair[0]); // okay pair[1] = "hello!"; // error }
Answered By - Mariusz Pawelski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.