【问题标题】:TypeScript factory pattern and property doesnt exist?TypeScript 工厂模式和属性不存在?
【发布时间】:2020-05-03 16:10:30
【问题描述】:

我即将使用 typescript 在我的 nodejs 应用程序上实现工厂模式,并使用以下代码进行测试:

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())

执行此操作时,我从控制台收到以下错误:index.ts:17:21 - error TS2339: Property 'pwd' does not exist on type 'userFactory'。

为什么我无法访问 Admin pwd 方法?你能给我解释一下吗?

谢谢

【问题讨论】:

  • Eugene 为您提供了一个明智的选择。但你想要一个解释。就这么简单,类的构造函数应该具有该类的返回类型。因此,在您的示例中发生的情况是将 new Admin() 强制转换为 userFactory,这是合法的,因为 userFactory 上没有 Admin 没有的属性。 userFactory 没有 pwd 方法,ergo。
  • 您好,感谢您的解释,非常感谢。

标签: typescript


【解决方案1】:

我认为最好不要从userFactory 构造函数返回一个新对象。您可以在您的工厂中使用 create 方法让代码按预期工作。

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());

【讨论】:

    猜你喜欢
    • 2016-07-05
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多