[英]How to define an array type with items of different types and with a specific order in TypeScript?
[英]how to limit array's type in specific order in typescript
如何在打字稿中以特定順序限制數組的類型,而不是定義范式。
這意味着,在ts中,我們只聲明了如下數組定義:
const arr:Array<any> = []
我想在定義數組中獲得特定的順序,例如:
const arr = ['string', 0, ...];
值只能是位置0處的字符串類型,並且只能是位置1處的數字類型...
謝謝
如果要將大小限制為2個元素,則可以使用元組來實現
const myTuple: [string, number] = ['test', 3]
或將元組類型定義提取到類型中
type myTupleType = [string, number]
const myTuple2: myTupleType = ['test', 3]
可以使用交集類型:
type OrderedArray<T> = Array<T> & {
0?: string;
1?: number;
}
const arr: OrderedArray<any> = ['string', 0, ...];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.