1

How do you map an instance of a derived class into an object which only contains the properties of it's base class?

interface Base {
    a: string;
}
interface Derived extends Base {
    b: string;
}

const derived: Derived = {
    a: 'hello',
    b: 'world'
}

const base: Base = derived;

console.log(base);

Output: { "a": "hello", "b": "world" } Desired output: { "a": "hello" }

Sure I could do:

const base: Base = {a:derived.a};

But this would get very tedious for more complex classes.

What's the best way to do this programmatically in Typescript?

Gabe O'Leary
  • 2,010
  • 4
  • 24
  • 41
  • 2
    Given that `Base` and `Derived` are [erased](https://github.com/Microsoft/TypeScript/wiki/FAQ#what-is-type-erasure) from the emitted JavaScript, you'll have to copy properties explicitly somewhere. The closest thing to programmatic I can think of is to use an array of property names. By the way, why do you want this? What's the use case where having extra properties causes a problem? – jcalz Sep 17 '20 at 16:48
  • The Derived class contains a lot of data some of which is being denormalized (firestore) - aka property 'a'. The entire purpose of maintaining multiple versions of the data is so that the we can read 'a' without having to read 'b', but using this approach results in the same thing being written to both places. – Gabe O'Leary Sep 17 '20 at 16:52
  • is there some way to generate an array of property names from the interface which can then be used at runtime to perform this operation? – Gabe O'Leary Sep 17 '20 at 16:53
  • 2
    Not with the standard TypeScript compiler there isn't. – jcalz Sep 17 '20 at 16:57

0 Answers0