I have a class defined like this
class Foo {
value: string | null;
constructor(){
this.value = null;
}
private ensureValueExists():this.value is string{ //type predicate is not legal
this.value = "bar";
return true;
}
doStuffWithValue(){
this.ensureValueExists();
return 5 + this.value; //ERROR, this.value can be null
}
}
I would like for the ensureValueExists method to be able to tell to the compiler that this.value is indeed a string and safe to use. Is there a special syntax to use or is it no doable with TS at the moment for methods ?
this.value ??= "bar";valuewill be initialised later but still would be available before "real code" (non-initialisation code) access it, then you can note it asvalue!: string. If you want null-safe access you can saythis.value ?? "fallback". If you want to make sure you produce an object wherevalueis treated as non-null you can have a separate interface. It's a bit hard to say which is the correct choice here.