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

Union types behave differently depending whether the variable is direct argument of the function #7830

Closed
zuzusik opened this issue Apr 5, 2016 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@zuzusik
Copy link

zuzusik commented Apr 5, 2016

TypeScript Version:

1.8.5

Code

type Result = boolean | string;
type GetResult = () => Result;
type ResultParam = GetResult | Result;

function getResult(result : ResultParam) {
  return result instanceof Function 
    ? result() 
    : result;
}

function getResultFromParams(params : {result : ResultParam}) {
  return params.result instanceof Function 
    ? params.result() 
    : params.result;
}

Code in Playground

Expected behavior:
script is compiled

Actual behavior:
compilation error is thrown on function getResultFromParams:
(13,7): error TS2349: Cannot invoke an expression whose type lacks a call signature.

@Arnavion
Copy link
Contributor

Arnavion commented Apr 5, 2016

Type guards don't narrow types of property expressions. See #3812

Edit: You can destructure params as a workaround:

function getResultFromParams({ result }: { result: ResultParam}) {
  return result instanceof Function 
    ? result() 
    : result;
}

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 5, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants