Set variable value via function in Typescript

821 Views Asked by At

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'
  }
}
2

There are 2 best solutions below

3
jered On

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 text is not undefined before trying to call a method on it.

if (text) {
  text.toUpperCase();
}

A conditional statement can inform TypeScript about the type of a variable because the only way the inner code will run is if text is not undefined.

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.

1
captain-yossarian from Ukraine On

Also you can use assertion functions

let text: string | undefined

function setText(str: string, variable: any): asserts variable {
  variable = str
}

setText('TypeScript test', text)

text.toUpperCase() // ok

However, please keep in mind, that text should be a part of function signature