Max Neumann
Max Neumann

Reputation: 363

Immutable function parameter typescript

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.

Upvotes: 7

Views: 2706

Answers (3)

Brandon Dyer
Brandon Dyer

Reputation: 1386

If you're looking for immutability to prevent your function from causing side effects, you can use the Readonly<T> type.

interface Person {
    name: string,
    age: number,
}

function add_age(person: Readonly<Person>) {
    person.age += 5; // not possible because it is immutable
}

add_age({ name: "Bob", age: 37 });

Upvotes: 3

Aron
Aron

Reputation: 9238

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

Upvotes: 3

Matthew Layton
Matthew Layton

Reputation: 42229

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.

Upvotes: 1

Related Questions