Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - assigning a base interface to the extended interface

Tags:

typescript

consider the following:

interface A {
  x:number;
  y:number
}

interface B extends A { 
  z:number;
}

let v2:B;
// compiler error, as z is not specified
v2 = getSomeA(); // assume this returns interface A

I have an interface B, that extends A. I have a function getSomeA() that returns interface A. My goal is to assign it to v2 and then add v2.z myself post the call. Obviously, this results in a compiler error. What is the right way to do what I intend to do ? (I could make z optional in interface B but that is not correct)

like image 793
user1361529 Avatar asked Oct 08 '17 12:10

user1361529


1 Answers

You could use object spread syntax for this:

v2 = { ...getSomeA(), z: 1 };
like image 116
Oblosys Avatar answered Nov 15 '22 05:11

Oblosys