2

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)

kaan_a
  • 3,503
  • 1
  • 28
  • 52
  • since js can't do that, and ts is supposed to be superset of js, it would result in everything being printed out, so there must be some other crazy way to do it. – tsamridh86 Jan 07 '22 at 14:46
  • js can do it. consider `const a = (({ a, b, c }) => ({ a, b, c }))(o)`. It's just a question of whether something like this has been added to typescript. – kaan_a Jan 07 '22 at 14:52
  • Typescript [is designed to not have types affect runtime](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals#non-goals) so you'll have to filter the keys manually. – Aplet123 Jan 07 '22 at 14:54
  • The type system doesn't exist at run-time. Therefore, it's not possible to match a run-time data like an object against a compile-time construct like an interface. You need something concrete to work with. – VLAZ Jan 07 '22 at 14:59
  • @VLAZ The type system does not need to exist at runtime for this to work. Typescript simply needs to compile something like: `const a = A of o` to something like `const a = (({ a, b, c }) => ({ a, b, c }))(o)` Based on @Aplet123's comment however, they might never implement something like this. Not, however, because they can't, rather because they don't want to. – kaan_a Jan 07 '22 at 15:15
  • Which leaves as in the same state - the type system does not exist at runtime. It does not exist now now, nor would it exist in the future. I do not think there is a difference how I phrase it - I chose to be more concise, because I did not feel it is necessary to explain that while TypeScript *could* do it in theory, however it would not do it in practice. I did not think it adds much value in a comment as it does not change the latter part of the comment. Namely, that *you* need to have your code working against something concrete which TypeScript would not remove. – VLAZ Jan 07 '22 at 15:26

0 Answers0