如何在 Typescript 中输入动态大小的数组? [英] How to type a dynamically sized array in Typescript?

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

问题描述

我想输入一个数组,其中第一个元素始终是数字,其余元素始终是字符串,并且长度至少为 1.

I want to type an array where the first element is always a number, and the rest of the elements are always strings, and the length as to be at least 1.

这是我最大的努力:

type MyArray =
  | [number]
  | [number, string]
  | [number, string, string]
  | [number, string, string, string];

我如何让它永远持续下去?

How do I make that go on forever?

推荐答案

在 TypeScript 3.0 之前,真的没有什么比您拥有的联合更好的了.但是随后引入了一系列相关的新功能以更好地支持元组类型,特别是它们与函数参数列表的关系.由于函数支持最终的 rest 参数将不确定数量的参数的类型表示为数组,引入最终的 元组中的其余元素 将无限数量的元组元素的类型表示为数组.

Before TypeScript 3.0 there really wasn't anything better than a union like you have. But then a bunch of related new features were introduced to better support tuple types, and specifically their relationship to lists of function parameters. And since functions support a final rest parameter representing the type of an indefinite number of parameters as an array, it made sense to introduce a final rest element in a tuple representing the type of an indefinite number of tuple elements as an array.

嘿,事实上,您的用例在文档中作为示例明确提及:

Hey, in fact, your use case is explicitly mentioned as an example in the documentation:

例如,[number, ...string[]] 表示具有 number 元素后跟任意数量的 string 元素的元组.

For example, [number, ...string[]] means tuples with a number element followed by any number of string elements.

那么让我们尝试一下:

type MyArray = [number, ...string[]];
const okay0: MyArray = [0]; // okay
const okay1: MyArray = [1, "a"]; // okay
const okay2: MyArray = [2, "a", "b"]; // okay
const okay3: MyArray = [3, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]; // okay

const bad0: MyArray = [0, "a", false]; // error!
//    ~~~~ <-- boolean is not assignable to string
const bad1: MyArray = ["x", "y"]; // error!
//                     ~~~ <-- string is not assignable to number
const bad2: MyArray = []; // error!
//    ~~~~ <--- property '0' is missing (i.e., bad2[0] is missing)

我觉得不错.希望有所帮助;祝你好运!

Looks good to me. Hope that helps; good luck!

链接到代码

这篇关于如何在 Typescript 中输入动态大小的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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