Typescript : Can't set default parameter value as false


I’ve a method which has some optional parameters, like this ,

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

I want to set the value of freehand as true only when needed , otherwise I want it as false,

but when i declare this

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

Im getting an error as

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


You just need to set the default value of freehand no need for ? it’s already optional consider this

function initializeInteraction(type: string, freehand: boolean = false) {
 // your magic

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

the only advantage of making the parameters as object is you can pass them with different order

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

you can short the function above like this

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

pass the parameter as object

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

both ways will give the same result 👍👍 , but they call initializeInteraction differently

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

Answered By – Muhammed Albarmavi

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.