microsoft / microsoft/TypeScript

Type discrimination in function calls for callable types doesn't work if discriminating property is optional

Open
#34,529 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.7.0-dev.20191015

Search Terms: type discrimination, callable, signatures, implicit any

Code

function test(
  a:
    | { type?: 1; property: (a: number) => void }
    | { type: 2; property: (a: string) => void },
) {
  return a.property
}


test({
  property: (x) => { // complaining that x implicitly has type any
    console.log('hi')
  },
})

Expected behavior:

x should be inferred to be number.

Actual behavior:

x is any.

If you change type?: 1 to type: 1, it works as expected.

Playground Link: link

Related Issues: #7294 (closed with #29011 - see second half of the original post, I believe it describes why this issue occurs)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided TypeScript 3.7 reproducer and compare the behavior with the required discriminant variant. Review related issue #7294 and its reference to #29011 for context on callable-type discrimination. Done means the optional discriminating property still infers the callback parameter as number rather than any.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.