Usage 1: a function declares its parameter won't be modified
This usage is very simple: as a contract, the function doSomething declares it doesn't mutate the received parameter.
interface Counter {
name: string
value: number
}
function doSomething(c: Readonly<Counter>) {
// ...
}
let c = {
name: "abc",
value: 123
}
doSomething(c)
// Here we are sure that 'c.name' is "abc" and 'c.value' is '123'
Usage 2: a factory declares that its output cannot be modified
With this code:
interface Counter {
readonly name: string
readonly value: number
inc(): number
}
function counterFactory(name: string): Counter {
let value = 0
return {
get name() {
return name
},
get value() {
return value
},
inc() {
return ++value
}
}
}
We have here a member readonly value that cannot be modified directly from the outside. But a member inc() can mutate the value. Also, the member value is declared as readonly but its value is changing.
I would like to know if this use of readonly on the member value is a good way to proceed. The syntax is OK. But is this example semantically correct in TypeScript? Is that what the modifier readonly is for?