Home > Software engineering >  Typescipt evaluates conditional types incorrectly
Typescipt evaluates conditional types incorrectly

Time:06-12

I have a very primitive code that for some reason gives a type error.

type ConfigEntry = {
  name?: string,
  value?: string
}

function parser1(c: ConfigEntry): Record<string, string> {
  const name = c.name;
  const value = c.value;
  return { name: value }; // fine, error since name can be undefined
}

function parser2(c: ConfigEntry): Record<string, string> | undefined {
  const name = c.name;
  const value = c.value;
  if (name === undefined) return undefined;
  else return { name: value }; // compiler still argues that name can be undefined
  // but in any circumstances it is not
}

If I understand TS correctly, compiler should examine conditions and evaluate types accordingly.

Also none of the other conditional expressions known to me work as well.

Example is enter image description here
So the correct code will be fixing the typo and specifying the return value as

Record<string, string | undefined>

function parser4(c: ConfigEntry): Record<string, string | undefined> | undefined {
  const name = c.name;
  const value = c.value;
  return name ? { [name]: value } : undefined;
}

Thank you all for the help.

  • Related