具有Readonly <>类型的继承

时间:2019-07-17 01:09:06

标签: typescript inheritance

我正在尝试通过继承设置一个不变的,嵌套的数据结构。类型是使用Readonly泛型类型构建的,并且需要其中一种Readonly类型才能扩展其他类型。

type Person = Readonly<{
  name : string
}>

type Student = Readonly<{
  school : string
}>

我需要学生扩展Person并具有只读名称属性。

2 个答案:

答案 0 :(得分:0)

您需要一个中间接口,例如InternalStudent,它将扩展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

答案 1 :(得分:0)

您可以这样做

type Person = Readonly<{
  name : string
}>

type Student = Person & Readonly<{
  school : string
}>

function x(s: Student) {
  s.name = "" // error
  s.school = "" // error
}
相关问题