Typescript - How to avoid repeating the same properties on an array of types?

Viewed 235

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',
       //...
    }
];
1 Answers

define a common styles variable then reuse it by spread operator:

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',
       //...
    }
];

Reference to spread operator:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Related