Take a look at this code snippet:
let str: string | null;
function print(msg: string) {
console.log(msg);
}
print(str);
When running this code, the typescript compiler correctly identifies the error, stating that Argument of type 'string | null' is not assignable to parameter of type 'string'.
This issue can be easily resolved by checking for the existence of str, like so:
let str: string | null;
function print(msg: string) {
console.log(msg);
}
if (str) {
print(str);
}
By adding this check, the code will compile without any errors. The typescript compiler is intelligent enough to recognize the validity of the check.
Now, let's say you want to check for 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 scenario, typescript does not understand that the call to the print method is safe. How can this be fixed?
EDIT
To clarify, here is a basic outline of my class:
However, my situation is a bit more intricate. This is the general 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) {
// perform an operation with the string
}
}
How can I resolve this issue in my specific case?