1

I'm trying to create a factory for instantiating my classes with generics. Checked out TypeScript docs and it all works perfectly. In short, this works just fine:

class Person {
    firstName = 'John';
    lastName = 'Doe';
}

class Factory {
    create<T>(type: (new () => T)): T {
        return new type();
    }
}

let factory = new Factory();
let person = factory.create(Person);

console.log(JSON.stringify(person));

Now define class Person in directory:

export class Person extends BasePerson {
    firstName = 'John';
    lastName = 'Doe';
}

And when I import Person from other package:

import { Person } from "./directory"

class Factory {
    create<T>(type: (new () => T)): T {
        return new type();
    }
}

let factory = new Factory();
let person = factory.create(Person);

I get error: Argument of type 'typeof Person' is not assignable to parameter of type 'new () => Person'

How can I get a value of Person instead of typeof Person?

Using TypeScript 3.7.2 and Node v10.13.0.

0

2 Answers 2

1

Could you try this for me please?

import { Person } from "./directory"

class Factory {
    create<T>(type: (new () => T)): T {
        return new type();
    }
}

let factory = new Factory();
let person = factory.create(new Person);
Sign up to request clarification or add additional context in comments.

5 Comments

thumbs up for the quick answer :) it is not a valid statement though, but I solved it. It is a little embarrasing, i had a parent class that expected an argument in its contructor, removed it and now everything works perfectly!
@pavle could you please add an answer how you solved your problem or - if this is really the correct answer - mark it with the green hook?
Your welcome @pavle, as mentioned by messerbill it might be a good idea to post your solution for any future folk who are experiencing a similar issue.
@InchHigh done. Inheritance was the problem, but with better dependency composition, problem was solved. Composition over inheritance!
Good stuff :) - Glad you sorted it.
0

Actual problem here was a parent class of Person -> BasePerson. BasePerson expected an argument in its constructor, so when I tried to call factory.create(Person), Person actually was an typeof because it expected an argument for base class constructor. Problem was solved by deleting the constructor in base class and injecting a property via ioc container, in my case Inversify.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.