Is there a way in typescript to explicitly indicate that a function is responsible for assigning value to a variable?
UPDATED CODE
Here, the code has been simplified. While getText()
ensures that it will never be undefined, this may not hold true in subsequent calls.
class MyClass {
text: string | undefined = undefined
setText = (str: string) => {
this.text = str
}
getText = (): string => {
/* The variable "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'
}
}