Search code examples
typescriptparametersimmutabilityoptional-parametersdefault-parameters

Are Immutable named parameters (with defaults) possible in Typescript (compile time)?


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.


Solution

  • 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.