Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript doesn't assume the value type in a ternary operator when it has been assigned before if the value is an object key #50356

Closed
albertothedev opened this issue Aug 18, 2022 · 1 comment

Comments

@albertothedev
Copy link

Bug Report

πŸ”Ž Search Terms

ternary operator, props object, object is possibly null

πŸ•— Version & Regression Information

  • This happens in version 4.7.4 and 4.8.0-beta

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type Props = {
  value: string | Array<string> | [] | null;
};

function example1(props: Props) {
  const isValueAnArray = Array.isArray(props.value);
  const isValueEmpty = !(isValueAnArray ? !!props.value.length : !!props.value);
                                                       ^ (property) value: string | string[] | [] | null
                                                          Object is possibly 'null'.
}

function example2(props: Props) {
  const isValueAnArray = Array.isArray(props.value);
  const isValueEmpty = !(Array.isArray(props.value) ? !!props.value.length : !!props.value); // No errors
}

function example3(value: string | Array<string> | [] | null) {
  const isValueAnArray = Array.isArray(value);
  const isValueEmpty = !(Array.isArray(value) ? !!value.length : !!value); // No errors
}

πŸ™ Actual behavior

example1 throws an error because TS thinks props.value might be null when checking its length.

πŸ™‚ Expected behavior

There should be no error, like in the other two functions.

@whzx5byb
Copy link

From #44730:

Narrowing through indirect references occurs only when the conditional expression or discriminant property access is declared in a const variable declaration with no type annotation, and the reference being narrowed is a const variable, a readonly property, or a parameter for which there are no assignments in the function body.

So you have to mark the property value readonly to make it work:

type Props = {
-  value: string | Array<string> | [] | null;
+  readonly value: string | Array<string> | [] | null;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants