为什么typescript中的“readonly”属性不起作用?

hgncfbus  于 6个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(106)
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);

字符串
为什么这没有抛出任何错误。你看到属性book_id是只读的。那么为什么当我试图赋值时,它没有抛出错误,book.book_id = 3?它没有违反只读吗?

b1payxdu

b1payxdu1#

因为Typescript中的readonly实际上不是readonly。
我不完全理解它,但你可以在这个Github问题中找到关于它的讨论:https://github.com/microsoft/TypeScript/issues/13002
作为一个程序员,我学习和成长的越多,我就越觉得那里有很多垃圾。只读就是垃圾,它不像你期望的那样“工作”。
你能做的最好的事就是不要做你现在在做的事。

ru9i0ody

ru9i0ody2#

我可以通过使用Readonly<T>来解决这个问题

class Foo {
   public bar: Readonly<string>
}

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

字符串

相关问题