[英]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.