如何在 TypeScript 中声明只读数组元组? [英] How do I declare a read-only array tuple in TypeScript?

查看:38
本文介绍了如何在 TypeScript 中声明只读数组元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在 TypeScript 中声明一个类型化的元组,例如,使用类型注释 [string, number].这意味着一个包含 2 个元素的数组,其中第一个元素需要是一个字符串,第二个元素需要是一个数字.

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.

我们还可以使用 ReadonlyArray 声明只读数组,这意味着字符串的只读数组.

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 3.4 版开始,您可以在元组类型前加上 readonly 关键字 (source).

From Typescript version 3.4 you can just prefix tuple type with readonly keyword (source).

TypeScript 3.4 还引入了对 readonly 元组的新支持.我们可以使用 readonly 关键字作为任何元组类型的前缀,使其成为 readonly 元组,就像我们现在可以使用数组速记语法一样.正如您所料,与可以写入插槽的普通元组不同,readonly 元组只允许从这些位置读取.

TypeScript 3.4 also introduces new support for readonly tuples. We can prefix any tuple type with the readonly keyword to make it a readonly 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
}

这篇关于如何在 TypeScript 中声明只读数组元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆