小编jst*_*olz的帖子

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

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

nullable typescript

19
推荐指数
2
解决办法
3万
查看次数

标签 统计

nullable ×1

typescript ×1