TypeScript - Cast SubClass to SuperClass

Viewed 537

is there a simple solution to the following problem? I want to cast the object B into the object A.

Thank your for your solutions.

export interface A {
  a: string;
}

export interface B extends A {
  b: string;
}

const b: B = {
  a: 'test1',
  b: 'test2'
};

console.log(b); //output: {a:'test1', b:'test2'}

console.log(b as A);  //output: {a:'test1', b:'test2'}, but i want {a:'test1'}

1 Answers

Interfaces are just a compile-time construct to ensure typesafety. You could create data like {'f': 'foo'} as any as A and it would still be perfectly valid, altough your data does not match the interface at all.

To "cast" this, you'd need to manually create a new object: const a = {a: b.a}.

Related