【问题标题】:Specifying a function which takes an 'options' objcet with default values指定一个函数,该函数采用具有默认值的“选项”对象
【发布时间】:2020-06-11 08:00:11
【问题描述】:

我想实现一个函数,它接受一个带有默认值的options 对象。

我知道该怎么做,但我想强制用户未指定的任何字段都将获得函数头中指定的默认值。

这是我目前所拥有的:

function func(options: {x: number; y: string;} = {x: 1, y: "1"}) {
    const x: number = options.x != undefined ? options.x : 1;
    const y: string = options.y != undefined ? options.y : "1";
    console.log(x, y);
}

当我在输出的 Javascript 文件上测试这个函数时,这很好用:

func();
func({});
func({x: 0});
func({y: "2"});
func({x: 3, y: "4"});

结果:

1 '1'
1 '1'
0 '1'
1 '2'
3 '4'

但是,感觉有点笨拙(特别是,我需要在两个不同的地方指定每个默认值)。

Typescript 中是否有已知的设计模式?

【问题讨论】:

    标签: typescript function default-value


    【解决方案1】:

    不需要在两个地方有默认值,你可以像这样缩短它:

    function func({ x = 1, y = "1" }: { x?: number; y?: string; } = {}) {
        console.log(x, y);
    }
    
    func();
    func({});
    func({ x: 0 });
    func({ y: "2" });
    func({ x: 3, y: "4" });
    

    如果您不需要显式类型,甚至更短:

    function func({ x = 1, y = "1" } = {}) {
        console.log(x, y);
    }
    

    结果:

    1 '1'
    1 '1'
    0 '1'
    1 '2'
    3 '4'
    

    【讨论】:

    • 我注意到它在省略 : { x?: number; y?: string; } 时也有效。那这样使用安全吗?即,类型是从对象字段的默认值推断出来的,而问号是从对象本身的默认值推断出来的吗?
    • 是的,TS 通过查看默认值自动推断参数类型。如果您有默认值,则隐式假定该参数是可选的 - 例如 function func(x = 3) {} // func(x?: number): void
    【解决方案2】:
    const defaults = {
       x: 1, 
       y: "1"
    }
    
    function func(options = defaults) {
        const x: number = options.x != undefined ? options.x : 1;
        const y: string = options.y != undefined ? options.y : "1";
        console.log(x, y);
    }
    

    这将完成你想要的。

    更紧凑:

    function func(options = { x: 1, y: "1" }) {
        const x: number = options.x != undefined ? options.x : 1;
        const y: string = options.y != undefined ? options.y : "1";
        console.log(x, y);
    }
    

    最紧凑:

    function func({x,y} = { x: 1, y: "1" }) {
       const _x = x ? x : 1;
       const _y = y ? y : "1";
       console.log(_x, _y);
    }
    

    TypeScript 根据提供的默认值推断类型。

    【讨论】:

    • 您的第一个建议非常明显。我可以自己想出那个。你的第二个看起来很像我的代码。我不想缩短我的代码,我想让它正确。据我了解 Typescript 背后的主要思想,删除类型是不正确的。
    • 第三个就够了。
    • 虽然您刚刚添加的Types are inferred from the defaults 是一条有用的信息(我在阅读您的建议后有点怀疑)。谢谢!!
    猜你喜欢
    • 2011-05-06
    • 2013-08-08
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多