0

I have function definition:

export function DivotTemplate(divot: Divot = {step: 8, triangleWidth: 4, radius: 0.6, strokeStyle: '#000'}, canvas: HTMLCanvasElement): HTMLCanvasElement {}

I want to be able pass not all object parameters like this:

DivotTemplate({step: 10});

As result to get this inside body of function:

{step: 10, triangleWidth: 4, radius: 0.6, strokeStyle: '#000'}

Is it possible?

  • What about this? https://stackoverflow.com/questions/26578167/es6-object-destructuring-default-parameters – A_A Aug 31 '21 at 10:19
  • You could also do `DivotTemplate(divot) { divot = { step: 8, triangleWidth: 4, /*...*/, ...divot } /* function body */ }` – A_A Aug 31 '21 at 10:20

1 Answers1

1

To call updateDivot({step: 10});, use Partial<Type>

interface Divot {
  step: number;
  triangleWidth: number;
  radius: number;
  strokeStyle: string;
}

function updateDivot(fieldsToUpdate: Partial<Divot>) {
  const divot: Divot = {
    step: 8,
    triangleWidth: 4,
    radius: 0.6,
    strokeStyle: '#000'
  };
  const updatedDivot = { ...divot, ...fieldsToUpdate };
  // use the object for further operations
}
naveen
  • 53,448
  • 46
  • 161
  • 251