4 ms·
TS allows you to pass a read-only object to a method taking a read-write value: type A = { value: number; } function test(a: A) { a.value = 3; } fu
by DexesTTP 2y ago
TS allows you to pass a read-only object to a method taking a read-write value:
type A = { value: number; }
function test(a: A) { a.value = 3; }
function main() {
const a: Readonly<A> = { value: 1 };
// a.value = 2; <= this errors out
test(a); // this doesn't error out
console.log(a); // shows 3
}
- thoweofasdf 2y agoNice find. Never ran into this because I haven't mutated inputs in over 15 years.
- tossandthrow 2y agoIt seems super weird that this type checks, and it appears to be some sort of corner case explicitly implemented. Normally typescript does not just allow implicit removal of a container type. Like, you can't pass Array<A> to a function that just takes A.