user15361861
user15361861

Reputation:

How to supplement the object with fields from default values?

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?

Upvotes: 0

Views: 26

Answers (1)

codeandcloud
codeandcloud

Reputation: 55200

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
}

Upvotes: 1

Related Questions