簡體   English   中英

如何在 TypeScript 中定義一個數組類型,它強制給定類型的多個元素?

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

我可以為字符串類型的 N 元素數組創建一個類型:

type A = string[];

以及預定義數量的元素,例如正好 2 個元素:

type A = [string, string];

我想要的是一種可以接受 2 個或更多元素的類型,但不僅僅是一個或一個都沒有。

type A = ?

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

這可能嗎?

您可以在元組類型中使用 rest 元素來指示元組類型是開放式的,並且可能有零個或多個數組元素類型的附加元素:

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

類型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 代碼鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM