microsoft / microsoft/TypeScript

Function expressions widen to `{}` in auto arrays

Open
#57,627 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

function expression widen widening auto array any empty objecr

🕗 Version & Regression Information
  • This is the behavior in every version I tried
⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.5.0-dev.20240304#code/MYewdgzgLgBAhgJwQRhgXhgbQLoG4BQ+iKAdAA4CuEAFgBQBmFYwUAluDLQJQwDe+MGAgCmUCgjAwARFIIBfLgSJJkBAPRqYAPQD8hUJFjEATOix5CJ8lTrd0APj4Cho8ZJnzFlpMfWbd+EA

💻 Code
const arr1 = [];

arr1.push(function () {
  return "";
});

arr1;
// ^? const arr1: {}[]

const arr2 = [];

arr2.push(() => {
  return "";
});

arr2;
// ^? const arr2: (() => string)[]
🙁 Actual behavior

arr1's type after this .push is {}[]

🙂 Expected behavior

I'd expect the type at both of the checked locations to be the same ((() => string)[])

Additional information about the issue

Likely the difference comes from the fact that the function expression is context-sensitive - maybe this is just a design limitation. However, the same doesn't happen in JS with expando objects (TS playground):

const obj = {}

obj.foo = function () {
  return ""
}

const result = obj.foo
//    ^? const result: () => string

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 TypeScript Playground example and compare the inferred types of arr1 and arr2 after their respective push calls. Use the additional JavaScript expando-object example as a comparison point; done means the function-expression and arrow-function cases have consistent inferred array element types, with regression coverage for the reported behavior.

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.