2

I'm trying to setup an immutable, nested data structure with inheritance. Types are built with the Readonly generic type and need one of such Readonly types to extend another.

type Person = Readonly<{
  name : string
}>

type Student = Readonly<{
  school : string
}>

I need Student to extend Person and have the readonly name property.

  • possible duplicate of https://stackoverflow.com/questions/41385059/possible-to-extend-types-in-typescript – AsukaSong Jul 17 '19 at 02:19

2 Answers2

0

You need intermediate interface, say InternalStudent, which will extends 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
Fyodor Yemelyanenko
  • 11,264
  • 1
  • 30
  • 38
  • Thanks, this works. I think I prefer @Henrik 's answer using intersection types because when creating a Student with an misshapen object literal, the message is more succinct: `Type '...' is not assignable to type 'Student'`, with the intermediate interface the message is `Type '...' is not assignable to type 'Readonly' – user3705060 Jul 17 '19 at 16:09
0

You could do this

type Person = Readonly<{
  name : string
}>

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

function x(s: Student) {
  s.name = "" // error
  s.school = "" // error
}
Henrik
  • 9,714
  • 5
  • 53
  • 87