首页 > 解决方案 > Typescript - How to avoid repeating the same properties on an array of types?

问题描述

In the example below, I have a group of ShadowStyles -> 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',
       //...
    }
];

标签: typescriptfigma

解决方案


定义一个通用样式变量,然后通过扩展运算符重用它:

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


推荐阅读