本文介绍了在 Typescript 中隐式创建元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有没有类型提示的方法可以在 Typescript 中创建元组.

Is there a way without type hinting to create a tuple in Typescript.

如果我只是这样做

const tuple = [1, 2];

元组的类型number[]

我能得到的最接近 oneliner 的是

The closest I can get to a oneliner is

const tuple: [number, number] = [1, 2];

我是否遗漏了什么,或者这是唯一的方法?

Am I missing something, or is this the only way?

推荐答案

从 TypeScript 3.4 开始,您可以在末尾添加简单的 as const.

As of TypeScript 3.4, you can add simply as const at the end.

const tuple = [1, 2] as const;

完全归功于 @bela53 的回答,其中有一个更好的示例和指向 TS 游乐场的链接.

Full credit to @bela53's answer, which has a better example and link to TS playground.

这篇关于在 Typescript 中隐式创建元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 07:13