如何在javascript中传递命名参数的默认值
我在typescript中有一个使用命名参数的方法,如下所示如何在javascript中传递命名参数的默认值,javascript,typescript,named-parameters,Javascript,Typescript,Named Parameters,我在typescript中有一个使用命名参数的方法,如下所示 public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) { } 参数m和n将从另一个对象提供,如 const default = { m : 'M', n :10, o:6 } 现在我想像下面那样调用foo,我想添加默认参数,而不在调用中显式传递它们 foo({x:'x', y: 5, z: 0}) 因此,我
public foo({x, y, z , m , n} : {x:string, y: number, z: number, m?:string, n?:number}) {
}
参数m
和n
将从另一个对象提供,如
const default = { m : 'M', n :10, o:6 }
现在我想像下面那样调用foo,我想添加默认参数,而不在调用中显式传递它们
foo({x:'x', y: 5, z: 0})
因此,我的问题是如何在foo
的主体中应用default
,或者在调用之前以某种方式拦截foo
,并应用default
public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
// for example how to apply default here
}
请注意,为了简单起见,我减少了参数的数量
我也知道下面这些解决方案,我已经在寻找一些较少的样板代码
public foo({x, y, z , m , n} = {x:string, y: number, z: number, m?:string, n?:number}) {
if (!m) {
m = default.m;
}
if (!n) {
n = default.n;
}
}
或
如何合并和销毁函数中的对象
typesometype={x:string,y:number,z:number,m?:string,n?:number};
常量initialValues={m:'m',n:10,o:6}
函数foo(对象:someType){
常数{x,y,z,m,n}={
…初始值,
…obj
}
}
对于合并,您需要使用de-structure
进行合并<代码>默认值分配在此处不起作用。仅当传递值时对象未定义时,默认赋值才用于工作。因此,您需要将默认值与传递的值合并
请检查代码中的注释
interface Foo {
x: string;
y: number;
z: number;
m?: string;
n?: number;
o?: number;
}
const defaultValue = { m: "M", n: 10, o: 6 } as Foo;
class A {
public foo(props: Foo) {
const { x, y, z, m, n } = { ...defaultValue, ...props };
console.log(x, y, z, m, n);
}
public foo2({ x, y, z, m = defaultValue.m, n = defaultValue.n }: Foo) {
// this will work, but verbose
console.log(x, y, z, m, n);
}
public foo1({ x, y, z, m, n }: Foo = defaultValue) {
// this will work only if foo1 called without argument
console.log(x, y, z, m, n);
}
public print() {
this.foo({ x: "x", y: 5, z: 0 }); // x 5 0 M 10
this.foo1(); // undefined undefined undefined 'M' 10
this.foo1({ x: "x", y: 5, z: 0 }); // x 5 0 undefined undefined
this.foo2({ x: "x", y: 5, z: 0 }); // x 5 0 M 10
}
}
const a = new A();
a.print();
foo
和foo2
功能将工作。然而,如果参数太多太少,那么foo2是非常冗长的。使用Object.assign()
或{…}
合并值。您只需在参数本身中添加一个默认值,如下所示:
public foo({x, y, z , m = 'a' , n = 10} = {x:string, y: number, z: number, m?:string, n?:number}) {
}
如果您传递一个值,默认值将被覆盖。通过这种方式,您甚至不需要使用if
来检查值的存在
您仍然可以按以下方式调用该方法:
foo({…默认值,x:x',y:5,z:0})代码>您可能可以在这里使用装饰器,但我不确定它是否会比foo({……默认值,x:'x',y:5,z:0})少很多样板文件代码>。不过,可能更易于重用。
public foo({x, y, z , m = 'a' , n = 10} = {x:string, y: number, z: number, m?:string, n?:number}) {
}