typescript - Typescript - How to avoid repeating the same properties on an array of types?
问题描述
In the example below, I have a group of ShadowStyle
s -> represented as type ShadowGroup
whose items are all instances of ShadowStyle
(the style
property is set to inherit an external library's ShadowEffect
type).
The thing is, there are some properties in ShadowStyle.style
that are always the same (marked below).
My question is: how do i avoid rewriting those same properties/values for every item in the array?
interface ShadowStyle {
name: string;
style: ShadowEffect; // type inherited from lib
}
type ShadowGroup = Array<MotifShadowStyle>;
const MyShadowGroup: ShadowGroup = [
{
name: 'Large',
style: {
type: 'DROP_SHADOW', // same for all items
visible: true, // same for all items
blendMode: 'NORMAL', // same for all items
color: {
r: 0,
g: 0,
b: 0,
a: 0.14,
},
offset: {
x: 0,
y: 8,
},
radius: 10,
spread: 1,
},
},
{
name: 'Medium',
//...
}
];
解决方案
定义一个通用样式变量,然后通过扩展运算符重用它:
const commonDefaultStyles = {
type: 'DROP_SHADOW', // same for all items
visible: true, // same for all items
blendMode: 'NORMAL' // same for all items
}
const MyShadowGroup: ShadowGroup = [
{
name: 'Large',
style: {
... commonDefaultStyles,
color: {
r: 0,
g: 0,
b: 0,
a: 0.14,
},
offset: {
x: 0,
y: 8,
},
radius: 10,
spread: 1,
},
},
{
name: 'Medium',
//...
}
];
参考传播运算符:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
推荐阅读
- sql-server - 如何使用连接显示不匹配的结果(sqlserver)
- html - 如何使用 freemarker 设置多选?提交“猫”列表以供选择
- html - 单击事件仅适用于表格 Angular 8 的第一页
- java - 如何检查 Firebase 消息服务是否处于启动完成状态?
- vim - 如何在插入模式下使 coc.nvim 检查代码的语义?
- dart - Dart 类型“int”不是“double”类型的子类型
- xamarin.forms - MapsUI 始终在 LatLng 0,0 处显示“自己的位置”标记
- smalltalk - Smalltalk 指的是尚未定义的类
- powershell - 权限不足,无法完成操作 - PowerShell 创建 Azure 广告应用失败
- php - 如何在 Magento 1 中应用我的自定义目录价格规则条件?