我试图建立一个不可变的、嵌套的继承数据结构。类型是用Readonly泛型类型生成的,需要一个这样的Readonly类型来扩展另一个。
type Person = Readonly<{
name : string
}>
type Student = Readonly<{
school : string
}>
我需要学生扩展人员并具有只读名称属性。
你可以这样做
type Person = Readonly<{
name : string
}>
type Student = Person & Readonly<{
school : string
}>
function x(s: Student) {
s.name = "" // error
s.school = "" // error
}
你需要中间接口,比如说< code>InternalStudent,它将扩展< code>Person
type Person = Readonly<{
name: string
}>
interface InternalStudent extends Person {
school: string
}
type Student = Readonly<InternalStudent>;
let student: Student = { school: '1', name: '2' } // OK
student.name = '1'; // Error
student.school = '2'; // Error