Home > other >  Typescript equality operator vs Array.includes checks
Typescript equality operator vs Array.includes checks

Time:10-28

I have prepared the demo (reproduction link)

Here is my question:

interface Person {
  target:
    | "first_name"
    | "last_name"
    | "date_of_birth"
    | "address_line"
    | "address_line2"
    | "city"
    | "state"
    | "zip";
}

interface Address {
  address_line?: string | null;
  address_line2?: string | null;
  state?: string | null;
  city?: string | null;
  zip?: string | null;
}

interface Owner {
  id: number;
  first_name: string;
  last_name: string;
  date_of_birth: string | null;
  address: Address
}

function createNewOnwer(target: Person["target"]) {
  const newData = {} as Partial<Owner>;

  if (
    target === "address_line" ||
    target === "address_line2" ||
    target === "zip" ||
    target === "state" ||
    target === "city"
  ) {
    // hover on target
    newData.address = {
      [target]: "test address" // typescript knows exactelly that target here is one of "address_line" | "address_line2" | "zip" | "state" | "city"
    };
  } else {
    newData[target] = String("test address"); // and here one of "first_name" | "last_name" | "date_of_birth"
  }
}

function createNewOnwerWithIncludeCheck(target: Person["target"]) {
  const newData = {} as Partial<Owner>;

  if (
    ["address_line", "address_line2", "zip", "state", "city"].includes(target)
  ) {
    // hover on target
    newData.address = {
      [target]: "test address" // ⬅️ why it doesn't know here that it is still one of  "address_line" | "address_line2" | "zip" | "state" | "city" ???            
  • Related