Home > Enterprise >  TypeScript: Inheritance from child to parent with inteface
TypeScript: Inheritance from child to parent with inteface

Time:09-23

Is it possible to get properties from child interface to the parent ?

exemple:

interface A {
title: string;
id: string;
}

interface B extends A {
author: string;
}

const book: A = {
title: 'my title',
id: '1',
// author is from interface B
author: 'author'
}

CodePudding user response:

book has to be of type B if you want it to have the author attribute

const book :B = { // <-- it's B not A
  title: 'test',
  id: 'idTest',
  author: 'authorTest' // <-- obtains this attribute from interface B
}
console.log(book);

Output

{
  "title": "test",
  "id": "idTest",
  "author": "authorTest"
} 

You can't have properties of B inside an object of type A because inheritance only work from top to bottom.

CodePudding user response:

Well, if you extend your interface A a bit with [prop: string]: unknown;, like this

interface A {
  title: string;
  id: string;
  [prop: string]: unknown;
}

interface B extends A {
  author: string;
}

const book: A = {
  title: 'my title',
  id: '1',
  // author is from interface B
  author: 'author',
};

then it will compile. However it a little bit defeats the purpose of types in TypeScript.

  • Related