TypeScript不遵循:没有初始化程序,并且在构造函数中未明确分配

时间:2020-05-12 10:44:33

标签: typescript

代码:

class Example {
    private server: string;
    constructor() {
        this.setServer();
    }
    setServer(): void {
        this.server = 'server';
    }
}

new Example();

错误:

⨯ Unable to compile TypeScript:
src/index.ts:309:13 - error TS2564: Property 'server' has no initializer and is not definitely assigned in the constructor.

309     private server: string;
                ~~~~~~

为什么没有跟随TypeScript?

1 个答案:

答案 0 :(得分:0)

不幸的是,它没有深入研究,仅检查构造函数,以防万一有人重写setServer方法并删除initialization

您可以使用以下选项之一:

  • 将其移至构造函数
  • 添加!
  • 设置默认值
  • 使其可选
class Example1 {
    private server: string;

    constructor() {
        this.server = 'server'; // <- here
    }
}
new Example1();

class Example2 {
    private server!: string; // <- here

    constructor() {
        this.setServer();
    }

    setServer(): void {
        this.server = 'server';
    }
}
new Example2();

class Example3 {
    private server: string = '';

    constructor() {
        this.setServer();
    }

    setServer(): void {
        this.server = 'server';
    }
}
new Example3();

class Example4 {
    private server?: string;

    constructor() {
        this.setServer();
    }

    setServer(): void {
        this.server = 'server';
    }
}
new Example4();