Consider the following code:
let str: string | null;
function print(msg: string) {
console.log(msg);
}
print(str);
in this case typescript compiler give me an error, saying correctly that Argument of type 'string | null' is not assignable to parameter of type 'string'.
This could simply fixed checking for str existence, so
let str: string | null;
function print(msg: string) {
console.log(msg);
}
if (str) {
print(str);
}
compile without errors. Typescript compiler i smart enough to understand the check.
Now suppose you check variable existence within a method, for example
let str: string | null;
function print(msg: string) {
console.log(msg);
}
function check(str: string) {
return str != null;
}
if (check(str)) {
print(str);
}
In this case typescrip do not understand that the call to print method is safe. How can I fix this?
EDIT
To be clear, this is (more or less) the skelethon of my class:
ok, but my case is a little bit more complex. This is, more or less the structure of my class:
class Clazz {
private myProp: {
aString?: string
anotherString?: number
};
constructor(aParam: any) {
this.myProp = {};
if (aParam.aString) {
this.myProp.aString = aParam.aString;
}
if (aParam.anotherString) {
this.myProp.anotherString = aParam.anotherString;
}
}
public haveAString() {
return this.myProp.aString != null;
}
public haveAnotherString() {
return this.myProp.anotherString != null;
}
public computation1() {
if (this.haveAString()) {
this.doAComputation(this.myProp.aString);
}
}
public computation2() {
if (this.haveAnotherString()) {
this.doAComputation(this.myProp.anotherString);
}
}
private doAComputation(str: string) {
// do something with the string
}
}
How should I fix in my case?