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

Typing fails on destructuring function params #33097

Closed
n1tin opened this issue Aug 27, 2019 · 2 comments
Closed

Typing fails on destructuring function params #33097

n1tin opened this issue Aug 27, 2019 · 2 comments

Comments

@n1tin
Copy link

n1tin commented Aug 27, 2019

Typescript version: 3.5.1

I was converting some of js files in React to ts when I faced this issue. I wanted to make some of props mandatory or optional based on value of a prop that is passed. The code in the component had destructed the variables from props causing this issue to occur.

Search Terms: destructuring

Code

Example:

type ErrorObj = {
  isError: true,
  errorMessage: string,
} | { isError:false, errorMessage?: string }

const checkError: (error: ErrorObj) => void = (error) => {
  error.isError && logLength(error.errorMessage);
}
const checkErrorAgain: (error: ErrorObj) => void = ({ isError, errorMessage }) => {
  isError && logLength(errorMessage); // throws an error, Type 'undefined' is not assignable to type 'string'.
}
const logLength = (message: string) => console.log(message.length);

Expected behavior: Should correctly infer the type of errorMessage param

Actual behavior: Incorrect type being inferred and an ts error is thrown

Playground Link: https://www.typescriptlang.org/play/index.html?jsx=2#code/C4TwDgpgBAogTnA9nA8gIwFZQLxQN4BQUUAlgM7xJwBcUwcArhADRFQQLICyEZZAhgHMItMvRIA7QawC+UAD75SFTjQBm-ADZkW7VTz5CIAflHipUGQQIBjRBLFQbACwg2A1pWS0AFByq0XqiYAJQ4AHxQAG6IJAAmOFB+qmHYkYTE-sgAdORBUABkBVCaiIIAMhBSwM7JVNlZcAYCwiEA3ARWdg7ATq4eQQCCgvySvo2BqugYqZEx8Yk+eMpBzHpUzUaWs-hseaqFxaUVVYI1ddy8LRDtnbb2jseV1c6LALZXRmZwkoI73WREJoINljj4PoZhKDTjVbkA

@jack-williams
Copy link
Collaborator

This is duplicate of #28599, which in turn is tracked here: #12184.

@n1tin
Copy link
Author

n1tin commented Aug 27, 2019

Closing it then 🙂.

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