Getter return type is any when object has a method and is passed through generic function

Viewed 24

I have the following code, where my getter's return type is any despite the real return type being obvious. There's some additional functions to trigger this behavior:

// This is required for repro
const wrapperFunction = <T>(obj: T) => obj;

const store = wrapperFunction({
  value: 'Super max',

  get simpleGetter() {
    return this.value;
  },

  // This is required for repro
  bark() {
    console.log('WUF');
  },
});

// This is any
const val = store.simpleGetter;
// This logs "Super max"
console.log(val);

Here's link to TypeScript playground: Full repro

1 Answers

Seems to be a TypeScript bug: https://github.com/microsoft/TypeScript/issues/49511

Easiest workaround is to write the return type manually or assign the object to a variable before passing it to generic function:

// This is required for repro
const wrapperFunction = <T>(obj: T) => obj;

const storeObj = {
  value: 'Super max',

  get simpleGetter() {
    return this.value;
  },

  // This is required for repro
  bark() {
    console.log('WUF');
  },
};
const store = wrapperFunction(storeObj);

// This is string now
const val = store.simpleGetter;
Related