【问题标题】:Typescript - How to avoid repeating the same properties on an array of types?Typescript - 如何避免在类型数组上重复相同的属性?
【发布时间】:2021-06-30 00:59:42
【问题描述】:

在下面的示例中,我有一组ShadowStyles -> 表示为ShadowGroup 类型,其项目都是ShadowStyle 的所有实例(style 属性设置为继承外部库的ShadowEffect类型)。

问题是,ShadowStyle.style 中有一些属性总是相同的(标记如下)。

我的问题是:如何避免为数组中的每个项目重写相同的属性/值?

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

【问题讨论】:

    标签: typescript figma


    【解决方案1】:

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

    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

    【讨论】:

    • 试过了;但 TS 抱怨是因为提供给 style 键的 ShadowEffect 类型似乎并不“知道”传播对象的结果。我原以为它能够看到 commonDefaultStyles 对象具有正确的结构?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多