Typescript:无法将默认参数值设置为 false

Typescript : Can't set default parameter value as false

我有一个方法有一些可选参数,像这样,

initializeInteraction(opts: { type?: string; freehand?:boolean= false }) {
    this._draw = this.drawService.initDraw({ drawtype: opts.type });
    this._drawInteraction = this._draw.interaction;
    this.mapService.addVector(this._draw.vector);
    this.mapService.addInteraction(this._drawInteraction);
  } 

我想仅在需要时将 freehand 的值设置为 true,否则我希望将其设置为 false

但是当我声明这个时

initializeInteraction(opts: { type: string; freehand?:boolean= false }) {}

我收到一个错误

[ts] A type literal property cannot have an initializer. [1247]

您真的需要将 typefreehand 包裹在 opts 对象中吗?

我建议这样做:

initializeInteraction(type: string, freehand?: boolean = false) {
    this._draw = this.drawService.initDraw({ drawtype: type });
    this._drawInteraction = this._draw.interaction;
    this.mapService.addVector(this._draw.vector);
    this.mapService.addInteraction(this._drawInteraction);
}

适用于 initializeInteraction 的当前实施。

编辑:

另一种选择是使用重载...

initializeInteraction(type: string);
initializeInteraction(freehand: boolean);
initializeInteraction(type: string, freehand: boolean);
initializeInteraction(param1: string | boolean, param2: boolean = false) {
    //type checking and implementation here...
}

这将允许您单独传递一个值,或同时传递两个值。

{ type: string; freehand?: boolean = false }

此类型字面量与 接口 的作用相同,因此无法提供默认值。幸运的是,默认情况下 freehand 的值将是未定义的(假的)。

您可以安全地将其替换为

initializeInteraction(opts: { type?: string; freehand?:boolean }) {
    // ...
    if (opts.freehand) {
        // Do stuff
    }
}

你只需要设置 freehand 的默认值不需要 ? 它已经是可选的考虑这个

function initializeInteraction(type: string, freehand: boolean = false) {
 console.log(type,freehand);
 // your magic
}

initializeInteraction('something');
initializeInteraction('something', false);
initializeInteraction('something', true);

将参数作为对象的唯一优点是您可以以不同的顺序传递它们

function initializeInteraction(opt:{ type:string , freehand?:boolean}) {
  let { type, freehand = false } = opt;
  console.log(type,freehand); 
  // your magic
}

你可以像这样缩短上面的函数

function initializeInteraction({type,freehand=false }: {type:string,freehand?:boolean}) {
  console.log(type,freehand);
  // your magic
 }

将参数作为对象传递

initializeInteraction({ type: 'something', freehand: false });
initializeInteraction({freehand: false, type: 'something' });
initializeInteraction({type: 'something' });

两种方式都会给出相同的结果,但它们调用 initializeInteraction 的方式不同

f('') ,f('',true)({type:'',freehand:true}) f({freehand:true,type:''}) , f({type:''})