TypeScript错误:使用联合时出现“(属性)没有初始化程序,并且在构造函数中未明确分配”

时间:2020-07-20 16:29:17

标签: typescript

Here是TS游乐场链接。选中identificationModestrictNullChecks时,我在strictPropertyInitialization上收到上述错误。如果我这样声明它,它就会消失:identificationMode: string = "Login",但随后我失去了使用联合定义identificationMode允许使用的字符串集所伴随的拼写检查。

import axios from "axios";

class MyClass {
  identificationMode: "Login" | "Welcome" | "Register";
  username: string = "";

  created() {
    axios.get("/user").then((res: any) => {
      this.username = res.data.username;
      this.identificationMode = "Welcome";
    });
  }

  handleLogout() {
    this.identificationMode = "Login";
  }

  handleLogin(param: string) {
    this.username = param.toUpperCase();
    this.identificationMode = "Welcome";
  }
}

2 个答案:

答案 0 :(得分:1)

使用联合类型作为类型注释,并使用初始值以获得所需效果

identificationMode: "Login" | "Welcome" | "Register" = "Login";

答案 1 :(得分:1)

该联合表示该属性不能是未定义的。因此,您可以立即(或在构造函数中)定义其值,或者将“未定义”添加到联合中,如下所示:

identificationMode: "Login" | "Welcome" | "Register" = "Login"; // Assign immediately

或:

identificationMode: "Login" | "Welcome" | "Register" | undefined;

任何一种方法都应该为您提供正确的结果,但我认为,如果您不希望在从该类创建对象时让该属性具有值,则第二种方法会更正确。