How to tell typescript that a function is responsible for assigning value to a variable?
EDITED CODE
The code is simplified. In getText() it will never be undefined, but it may be that in another call it will be undefined.
class MyClass {
text: string | undefined = undefined
setText = (str: string) => {
this.text = str
}
getText = (): string => {
/* "this.text" will never be undefined */
if (!this.text) {
this.setText('TS test')
//this.text = 'TS test' /* No TS error */
}
return this.text // => TS ERROR: Type 'undefined' is not assignable to type 'string'
}
}
You can't. Generally it would be bad practice to set variables outside of the scope of the function anyway.
If you want to keep that pattern however, you can use a type guard to safely check that
textis notundefinedbefore trying to call a method on it.A conditional statement can inform TypeScript about the type of a variable because the only way the inner code will run is if
textis notundefined.In general if you stick with this "global variable" pattern with setters, you should go along with TypeScript's effective behavior of treating those variables as if they could be anything in the union type -- because it easily can be any of those types.