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.
asked Aug 01 '26 04:08
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With