user3137766
user3137766

Reputation:

TypeScript factory pattern and property doesnt exist?

I'm about to implement factory pattern on my nodejs app with typescript with following code for testing :

class userFactory {
  public constructor(type:string) { return new Admin() }
}

class Admin {
  public type:string;
  constructor(){
    this.type = "admin"
  }
  public pwd(){ return "200" }
}

let factory = new userFactory('admin');
console.log(factory.pwd())

When executing this, from console i receive following error : index.ts:17:21 - error TS2339: Property 'pwd' does not exist on type 'userFactory'.

Why i cannot access the Admin pwd method? could you explain me please ?

thank you

Upvotes: 0

Views: 186

Answers (1)

Eugene Karataev
Eugene Karataev

Reputation: 1971

I think it's better not to return a new object from the userFactory constructor. You can use a create method in your factory for code to work as expected.

class userFactory {
    create(type: string) {
        return new Admin();
    }
}

class Admin {
  public type:string;
  constructor(){
    this.type = "admin"
  }
  public pwd(){ return "200" }
}

let factory = new userFactory();
let admin = factory.create('admin');
console.log(admin.pwd());

Upvotes: 0

Related Questions