为什么打字稿中的“只读”属性不起作用?

问题描述 投票:0回答: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);

为什么这没有给我带来任何错误。您会看到属性 book_id 是只读的。那么,当我尝试分配 book.book_id = 3 时,为什么它不会在这里抛出错误呢?不违反只读吗?

typescript interface readonly
2个回答
3
投票

因为 Typescript 中的 readonly 实际上并不是只读的。

我不完全理解它,但你可以在这个 Github 问题中找到关于它的讨论:https://github.com/microsoft/TypeScript/issues/13002

作为一名程序员,我学习和成长得越多,我就越觉得外面有很多垃圾。 Readonly 很糟糕,它不会按照您期望的方式“正常工作”。

你能做的最好的事情就是不要做你在这里做的事情。


0
投票

我可以通过使用

Readonly<T>

来解决这个问题
class Foo {
    property bar: Readonly<string>
}

fooInstance.bar = 'test'; // <- compile-time error
© www.soinside.com 2019 - 2024. All rights reserved.