打字稿:无法将默认参数值设置为 false

Aha*_*iPK 7 typescript angular angular5

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

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);
  } 
Run Code Online (Sandbox Code Playgroud)

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

但是当我宣布这一点时

initializeInteraction(opts: { type: string; freehand?:boolean= false }) {}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误

[ts] A type literal property cannot have an initializer. [1247]
Run Code Online (Sandbox Code Playgroud)

mal*_*awi 10

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

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

initializeInteraction('something');
initializeInteraction('something', false);
initializeInteraction('something', true);
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

将参数作为对象传递

initializeInteraction({ type: 'something', freehand: false });
initializeInteraction({freehand: false, type: 'something' });
initializeInteraction({type: 'something' });
Run Code Online (Sandbox Code Playgroud)

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

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