通过函数在 TypeScript 中设置变量的值

huangapple go评论70阅读模式
英文:

Set variable value via function in Typescript

问题

如何告诉 TypeScript 一个函数负责为变量赋值?

编辑后的代码

代码已经简化。在 getText() 中它永远不会是 undefined,但在另一个调用中可能会是 undefined。

class MyClass {
  
  text: string | undefined = undefined
  
  setText = (str: string) => {
    this.text = str
  }
  
  getText = (): string => {

    /* "this.text" 永远不会是 undefined */
    if (!this.text) {
      this.setText('TS test')
      //this.text = 'TS test' /* 没有 TS 错误 */
    }

    return this.text // => TS 错误: 类型 'undefined' 不能赋值给类型 'string'
  }
}
英文:

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

答案1

得分: 2

你不能这样做。通常来说,在函数的作用域之外设置变量都是不好的实践。

如果你想保持这种模式,你可以使用 类型保护 来安全地检查 text 在尝试调用方法之前是否为 undefined

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

条件语句可以告诉 TypeScript 变量的类型,因为内部代码只有在 text 不为 undefined 时才会运行。

一般来说,如果你坚持使用这种“全局变量”的模式与 setters,你应该遵循 TypeScript 的有效行为,将这些变量视为联合类型中的任何类型,因为它很容易就可以是其中的任何一种类型。

英文:

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.

答案2

得分: 0

你可以使用断言函数

let text: string | undefined

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

setText('TypeScript test', text)

text.toUpperCase() // ok

然而,请记住,text 应该是函数签名的一部分

英文:

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

huangapple
  • 本文由 发表于 2023年6月16日 08:14:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定