我有一个带有一些可选参数的方法,例如
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]
答案 0 :(得分:0)
您真的需要将type
和freehand
包装在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...
}
这将允许您单独传递一个值,或传递两个值。
答案 1 :(得分:0)
您只需要设置手绘的默认值即可,不需要?
,这已经是可选的,请考虑
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:''})
答案 2 :(得分:-1)
{ type: string; freehand?: boolean = false }
此类型文字与接口的作用相同,因此无法提供默认值。幸运的是,默认情况下freehand
的值是未定义的(falsey)。
您可以放心地将其替换为
initializeInteraction(opts: { type?: string; freehand?:boolean }) {
// ...
if (opts.freehand) {
// Do stuff
}
}