【发布时间】: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