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