我正在编写服务,运行该服务时出现以下错误。
有问题的部分是:

import { Configuration } from "./Configuration";
import { BooksApplication } from "./application/BookApplication";
import { PersistenceBookRepository } from "./application/PersistenceBookRepository";
import { DatabaseAccessor } from "./database/DatabaseAccessor";

export class Context {
  public readonly configuration: Configuration;

  public constructor(configuration: Configuration) {
    this.configuration = configuration;
  }

  private readonly databaseAccessor = new DatabaseAccessor(
    this.configuration.databaseConfiguration
  );

  private readonly bookRepository = new PersistenceBookRepository(
    this.databaseAccessor
  );

  private readonly bookService = new BooksApplication(this.bookRepository);
}


错误:

TypeError: Cannot read property 'databaseConfiguration' of undefined
    at new Context (/sandbox/src/Context.ts:14:24)
    at Object.<anonymous> (/sandbox/src/index.ts:6:17)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
error Command failed with exit code 1.


我检查了从Typescript生成的代码,它看起来像这样:

// ...
var Context = (function () {
    function Context(configuration) {
        this.databaseAccessor = new DatabaseAccessor_1.DatabaseAccessor(this.configuration.databaseConfiguration);
        this.bookRepository = new PersistenceBookRepository_1.PersistenceBookRepository(this.databaseAccessor);
        this.bookService = new BooksApplication_1.BooksApplication(this.bookRepository);
        this.configuration = configuration;
    }
    return Context;
}());
// ...


如您所见,this.configuration = configuration;位于末尾,因此this.databaseAccessor = new DatabaseAccessor_1.DatabaseAccessor(this.configuration.databaseConfiguration);失败。

我做错了什么还是Typescript中有错误?

我试图更改类成员的顺序,但结果相同。

我有一个项目在这里重现该问题:https://codesandbox.io/embed/644k5kwr4r

谢谢。

最佳答案

实际上,这是根据spec proposal¹的正确启动顺序:


  当评估字段初始值设定项并将字段添加到实例时:
  
  
  基类:在构造函数执行的开始,甚至在参数分解之前。
  派生类:在super()返回之后。 (super()调用方式的灵活性导致许多实现为此情况创建了一个单独的不可见的initialize()方法。)
  


TLDR:类字段首先在构造函数体之前执行。

您可以将初始化移到构造函数中。



¹由于TS是JS的超集,因此它也必须符合ES规范。

10-07 19:35
查看更多