0

The following example (which unfortunately doesn't work) should illustrate this question:

function test({ name = 'Bob', age = 18 }: { readonly name?: string, readonly age?: number }) {
  // this should result in an error (but doesn't):
  name = 'Lisa';
}

This interesting article has some infos how to achieve Immutability with parameters, but AFAIK, this doesn't work with default parameters.

1 Answers1

2

You might consider this a workaround, but you're not really passing 'named parameters', you are passing an object.

So this can be fairly easily rewritten as:

function test(args: { name?: string, age?: number }) {
  const { name = 'Bob', age = 18 } = args;
  // this will error
  name = 'Lisa';
}

The reason readonly doesn't carry over, is because you're creating entirely new variables. readonly only applies to the object's properties, but not their values.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • Thanks, your solution comes very close to the optimum (which would be as you mentioned, *real* named parameters)! Indeed they are not default parameters, but it's AFAIK the closest to default parameters. – Philipp Mildenberger Jul 03 '20 at 23:11