Alberto Vilches
Alberto Vilches

Reputation: 333

TypeScript error: "(property) has no initializer and is not definitely assigned in the constructor" when using a Union

Here's a TS playground link. I get the error above on identificationMode when having strictNullChecks and strictPropertyInitialization checked. It disappears if I declare it as this: identificationMode: string = "Login" but then I lose the spell checking that comes with using a Union to define the set of strings that identificationMode is allowed to be.

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";
  }
}

Upvotes: 0

Views: 467

Answers (2)

Asher Kleiman
Asher Kleiman

Reputation: 149

That union implies that the property CAN'T be undefined. So either you define its value right away (or in a constructor) OR you add to the union the 'undefined', like this:

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

or:

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

Either way should give you the right result but, in my opinion, the second one would be more correct if you don't want the property to have a value when you create an object from that class.

Upvotes: 1

Aluan Haddad
Aluan Haddad

Reputation: 31803

Use the union type as your type annotation along with an initial value for the desired effect

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

Upvotes: 1

Related Questions