Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable function parameter typescript

Tags:

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.

like image 490
Max Neumann Avatar asked Aug 01 '26 04:08

Max Neumann


1 Answers

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 });
like image 175
Brandon Dyer Avatar answered Aug 02 '26 17:08

Brandon Dyer