我怎么能在打字稿中返回一个可为空的值

jst*_*olz 19 nullable typescript

在 NPM 模块中,我使用打字稿

  "devDependencies": {
    "@types/node": "^8.0.0",
    "typescript": "^2.8.1"
  }
Run Code Online (Sandbox Code Playgroud)

我想使用公共方法返回一个私有的可为空参数。请参考下面的例子。我看到的错误是

Property 'string1' has no initializer and is not definitely assigned in the constructor.
Run Code Online (Sandbox Code Playgroud)

如果我在构造函数中分配了一个 undefined 我得到了错误

[ts]
Type 'string | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'
Run Code Online (Sandbox Code Playgroud)

我应该如何在打字稿中做到这一点,我来自 c# 方面:)

export class HowToDoThis {

    private string1?: string;

    public constructor() {

        //this.string1 = undefined;
    }

    public add2String1(content: string) {

        this.string1 += content;
    }

    public getString1(): string {

        return this.string1;
    }
}
Run Code Online (Sandbox Code Playgroud)

tru*_*ru7 17

你可以定义

private string1: string | undefined;
Run Code Online (Sandbox Code Playgroud)

  • 是的,但我更喜欢这种更具描述性的表达方式。无论哪种方式都不会影响最终文件大小,因为这些详细信息不会传递到生成的 js。 (3认同)

小智 -4

不确定您想做什么?为什么你希望它是未定义的?我认为您不想将内容与“未定义”连接起来。

所以使用:

private string1 = "";
Run Code Online (Sandbox Code Playgroud)

或者

private string1: string;
public constructor() {
    this.string1 = "";
}
Run Code Online (Sandbox Code Playgroud)