microsoft / microsoft/TypeScript

Union of functions with typed `this`, fails with no parameters

Open
#41,213 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: This-Typing Help Wanted
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 4.0.2

Code

interface Context {
  hello: boolean
}

type OptionsTest =
      | ((this: Context) => void)
      | ((this: Context) => PromiseLike<any>)
      | ((this: Context, done: boolean) => void)

function container (test: OptionsTest) {

}

// This does not work!

container(function () {
  console.log(this.hello);
})

// This works!

container(function (done) {
  console.log(this.hello);
})

// This works!

type Single = (this: Context) => void;
function SingleContainer (test: Single) {}
SingleContainer(function () {
  console.log(this.hello)
})

Expected behavior:

Correctly provide this type to (typed union) functions without arguments.

Actual behavior:

No this type is being provided for functions without arguments.

Playground Link

StackOverflow Link

Search Terms

  • contextually typed
  • this parameter
  • union of functions

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 with the linked Playground reproduction and compare contextual typing for the union in OptionsTest with the single-function Single type. Trace the compiler's handling of contextual typing, typed this parameters, and unions of functions. Done means the no-parameter callback receives Context.this while the existing parameterized and single-function cases continue to work, with regression coverage added where appropriate.

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
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.