How to filter an object's properties by an interface

Viewed 24

Let's say we have two interfaces defined as such:

interface A {
  a: string;
  b: number;
  c: Array<number>;
}

interface B {
  x: number;
  y: number;
  z: number;
}

And another type defined as such:

type C = A & B;

or

interface C extends A, B {}

How can I get an object that only contains the properties of an object of type C that belong to the interface A or B?

The following does not do the trick:

function f(o: C) {
  const a = o as A;
  const b = o as B;

  console.log("A:", a);
  console.log("B:", b);
}

But if it did, then the output of the following code:

const t: C = {
  a: "Test",
  b: 1,
  c: [0, 1],
  x: 1,
  y: 1,
  z: 0,
};

f(t);

Would be:

A: { a: "Test", b: 1, [0, 1] }
B: { x: 1, y: 1, z: 0 }

Is it possible to do what I need?

Perhaps something like:

const a = { ...A } = o;

(Which, obviously, also doesn't work, it won't even compile)

0 Answers
Related