0

I am looking for a way to have "direct" access methods of UserRepo and DogRepo from within Sys. By "direct" I mean this.findDog not this.dogRepo.findDog. Is it possible to "spread" or mixin the methods from UserRepo and DogRepo respectively so that I can use them within Sys?

class RBase {
    baseFind = (x: string) => (v: string) => {}
    baseCreate = (x: string) => (v: string) => {}
}

class UserRepo extends RBase {
    findUser = this.baseFind('user')
    createUser = this.baseCreate('user')
}

class DogRepo extends RBase {
    findDog = this.baseFind('dog')
    createDog = this.baseCreate('dog')
}

class Sys {
    example () {
        this.findDog
        this.createUser
    }
}

I am basically looking for a way to extend more than one class.

Update, I tried this and it did not work:

export default 'example'

class RBase {
    baseFind = (x: string) => (v: string) => x
    baseCreate = (x: string) => (v: string) => x
}

class UserRepo extends RBase {
    findUser = this.baseFind('user')
    createUser = this.baseCreate('user')
}

class DogRepo extends RBase {
    findDog = this.baseFind('dog')
    createDog = this.baseCreate('dog')
}

interface Sys extends UserRepo, DogRepo {}
class Sys {
    example () {
        this.findDog('fido')
        this.createUser('michael')
    }
}

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            Object.defineProperty(derivedCtor.prototype, name,
                // @ts-ignore
                Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
        });
    });
}

applyMixins(Sys, [UserRepo, DogRepo])

const s = new Sys()
s.example()
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • Possible duplicate of [Typescript: How to extend two classes?](https://stackoverflow.com/questions/26948400/typescript-how-to-extend-two-classes) – jcalz Nov 08 '19 at 17:20
  • Documentation for [mixins](http://www.typescriptlang.org/docs/handbook/mixins.html) – jcalz Nov 08 '19 at 17:20

1 Answers1

0

This works, not sure if it's best though.

interface Sys extends UserRepo, DogRepo {}
class Sys {
    constructor() {
        Object.assign(this, new UserRepo())
        Object.assign(this, new DogRepo())
    }
    example () {
        console.log(this.findDog('fido'))
        console.log(this.createUser('michael'))
    }
}
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424