Why does typescript allow assignment of a readonly type to a non-readonly?

26 views Asked by At

I am surprised that I can assign a readonly type to its mutable type, thus surpassing the immutability feature.

export class Todo {
    constructor(
        public name: string,
        public active = true,
        public completed = false,
        public editing = false) { }
    public toString() { return this.name }
}

function f() {
    let ro: Readonly<Todo> = new Todo("bugs bunny")
    ro.name = "duffy duck" // Cannot assign to 'name' because it is a read-only property. ts(2540)
    let t: Todo = ro // allowed!
    t.name = "duffy duck" // so we can modify
}

The problem is that we can pass readonly instances to functions that require mutable instances and then mutate them.

Is there a way to enforce immutablility better in typescript?

0

There are 0 answers