如何在 TypeScript 中声明只读数组元组?

编程入门 行业动态 更新时间:2024-10-08 08:28:27
本文介绍了如何在 TypeScript 中声明只读数组元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我们可以在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 10:23:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1188569.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   声明   如何在   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!