简体   繁体   English

如何在 TypeScript 中定义一个数组类型,它强制给定类型的多个元素?

[英]How to define an array type in TypeScript which enforces more than one element of a given type?

I can create a type for an array of N element of string type:我可以为字符串类型的 N 元素数组创建一个类型:

type A = string[];

as well as a predefined number of elements, such as exactly 2 elements:以及预定义数量的元素,例如正好 2 个元素:

type A = [string, string];

What I am trying to have is a type that will accept 2 or more elements, but not just one or none.我想要的是一种可以接受 2 个或更多元素的类型,但不仅仅是一个或一个都没有。

type A = ?

A = ['a', 'b'];  // OK 
A = ['a', 'b', 'c'];  // OK 
A = ['a', 'b', ... 'N'];  // OK 
A = ['a'];  // Error
A = [];  // Error

Is this possible?这可能吗?

You can use rest elements in tuple types to indicate that the tuple type is open-ended and may have zero or more additional elements of the array element type:您可以在元组类型中使用 rest 元素来指示元组类型是开放式的,并且可能有零个或多个数组元素类型的附加元素:

type A = [string, string, ...string[]];

The type A must start with two string elements and then it can have any number of string elements after that:类型A必须以两个string元素开头,然后可以有任意数量的string元素:

let a: A;
a = ['a', 'b'];  // OK 
a = ['a', 'b', 'c'];  // OK 
a = ['a', 'b', 'c', 'd', 'e', 'N'];  // OK 
a = ['a'];  // error! Source has 1 element(s) but target requires 2
a = [];  // error!  Source has 0 element(s) but target requires 2.

Playground link to code Playground 代码链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM