[英]TypeScript: Initialize interface like array (without specifying member name)
我有一個界面:
interface Rect {
width: number
height: number
}
我可以這樣初始化它:
const SomeRect : Rect = {
width: 5,
height: 10
};
但是,我可以像數組一樣初始化它嗎?
const SomeRect : Rect = [5, 10];
如果我嘗試初始化一個接口數組,這可能會很有用,例如:
const SomeRects : Array<Rect> = [
[5, 10],
[15, 20],
[30, 50]
];
PS:我不想使用數組,因為我無法按名稱獲取成員(寬度和高度),而只能通過索引。
您想要的大部分內容都可以通過Tuple 類型來實現。
您可以將Rect
定義為長度為 2 的數組,其中兩個元素的類型均為number
。
type Rect = [number, number]
您的SomeRect
和SomeRects
示例均適用此定義。
const SomeRect: Rect = [5, 10];
const SomeRects: Array<Rect> = [
[5, 10],
[15, 20],
[30, 50]
];
PS:我不想使用數組,因為我無法按名稱獲取成員(寬度和高度),而只能通過索引。
為了支持按名稱訪問,您需要轉換為 object 或使用幫助程序 function。
使用解構而不是數字索引的助手:
const rectWidth = ([width]: Rect) => width;
const rectHeight = ([_, height]: Rect) => height;
轉換(類似於@Aluan Haddad 的評論):
interface KeyedRect {
width: number
height: number
}
const toKeyedRect = ([width, height]: Rect) => ({
width,
height
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.