2
interface ReadExample {
    readonly book_id: number,
    book_name: string
}

class Book implements ReadExample{
    book_id= 3;
    book_name = 'A Thousand Stars';
    constructor(book_id:number, book_name:string){
        this.book_id = book_id;
        this.book_name = book_name;
    }

}
let book: Book = new Book(2, 'Sis');
console.log(book);
book.book_name = 'Sister';
book.book_id = 3;
console.log(book);

Why is this not throwing me any error. You see the property book_id is readonly. So why does it not throw an error here when I try to assign, book.book_id = 3? Does it not violate readonly?

2 Answers 2

4

Because readonly in Typescript is not actually readonly.

I don't fully understand it but you can find a discussion on it in this Github issue: https://github.com/microsoft/TypeScript/issues/13002

The more I learn and grow as a programmer the more I feel theres a lot of crap out there. Readonly is just crappy, it doesn't "just work" the way you'd expect it to.

The best you could do is not do what you're doing here.

Sign up to request clarification or add additional context in comments.

1 Comment

Haha, yes. Thoroughly enjoyed reading the comments in that GitHub issue. Thank you @BigBadBeny. :)
1

I was able to work around this by using Readonly<T>

class Foo {
   public bar: Readonly<string>
}

fooInstance.bar = 'test'; // <- compile-time error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.