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