[英]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]
你只需要設置 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:''})
您真的需要在opts
對象中包裝type
和freehand
up 嗎?
我建議這樣做:
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.