Microsoft/TypeScript

Return type is `any` of getter in object passed as generic

Open

#49,511 opened on Jun 13, 2022

View on GitHub
 (2 comments) (6 reactions) (0 assignees)TypeScript (6,726 forks)batch import
BugDomain: This-TypingHelp Wanted

Repository metrics

Stars
 (48,455 stars)
PR merge metrics
 (Avg merge 6d 17h) (9 merged PRs in 30d)

Description

Bug Report

When the following is true:

  • You are passing an object created inline to a function
  • The type of that function argument is generic
  • The object has a getter that accesses this
  • The object also has a function

Then the return type of the getter will be any.

If you either remove the function from the object or create the object before passing it into the function the getter will return the correct type.

🔎 Search Terms

any, object, generic

🕗 Version & Regression Information

  • Bug present in all versions available on the playground, including nightly

⏯ Playground Link

Playground link with relevant code

💻 Code

declare function generic<T>(v: T): T;

// Passing object directly to genery gives type `any` on `get hi()`
const store = generic({
  hello: "hi",

  // return type of getter is any
  get hi() {
    return this.hello;
  },

  // If you remove this function, return type of getter will be string
  doSomething() { }
});

const res = store.hi // any

// Passing object directly to genery gives type `any` on `get hi()`
const obj = {
  hello: "hi",

  // return type of getter is string
  get hi() {
    return this.hello;
  },

  doSomething() { }
};
const store2 = generic(obj)

const res2 = store2.hi // string

🙁 Actual behavior

Return type of getters are any

🙂 Expected behavior

Return type of getters have the type of the returned data

Contributor guide