Immutable function parameter typescript

Viewed 956

Is there a way how you can get immutability in typescript of function parameters? (the same from java with final)

Example:

function add(a: number, b: number): number {
    a = 5; // possible
    return a + b;
}

And what I am searching for, example:

function add(a: ???, b: ???): number {
    a = 5; // not possible because it would be immutable
    return a + b;
}

I am searching this because of clearity if a function can modify my parameters.

3 Answers

It's a little hacky but you can enforce it like this

function add(...params: readonly [a: number, b: number]): number {
  const [a, b] = params;
  a = 5;
//^^^^^
//Cannot assign to 'a' because it is a constant.

  return a + b;
}

a and b are now constants and therefore immutable.

Note however that although params is readonly that only prevents you from doing things like pushing or splicing the tuple array. It won't prevent you from reassigning the array altogether

In addition to Aron's answer, you could also allow add to take 0..n arguments and make them readonly:

function add(...args: readonly number[]): number {
    args[0] = 123; // not allowed!

    return args.length === 0 ? 0 
        : args.length === 1 ? args[0] 
        : args.reduce((a, b) => a + b);
}

add() // 0
add(123) // 123
add(123, 456) // 579
add(123, 456, 789) // 1368

...again, it's hacky but it works.

You can use the Readonly<T> type.

function add(a: Readonly<number>, b: Readonly<number>): number {
    a = 5; // not possible because it is immutable
    return a + b;
}
Related