Matthieu Riegler
Matthieu Riegler

Reputation: 55971

Why would mapped type trigger a compilation error when called within class

Here is my sample code.

Calling get within the class triggers an error while calling the method outside works fine.

Any idea why ?

type DefinedKeys<T> = keyof {
  [K in keyof T as undefined extends T[K] ? never : K]: K
}

class MyAbstractClass {
  get<K extends keyof this & DefinedKeys<this>>(key: K): this[K] {
    return this[key];
  }
}

class MyClass extends MyAbstractClass {
  foo: string = "ok";
  optional?: string;

  test() {
    this.get('foo'); // Doesn't work 
  }
}

const instance = new MyClass();
const yepItsWorks: string = instance.get("foo"); // Ok

TS Playground

Upvotes: 1

Views: 60

Answers (1)

phry
phry

Reputation: 44354

My guess is that withing test the execution context is not known.

TypeScript assumes correctly that you could call the method with a different this using instance.test.call(otherThis) or similar. If you explicitly type this, it works.

class MyClass extends MyAbstractClass {
  foo: string = "ok";
  optional?: string;

  test(this: MyClass) {
    this.get('foo'); // Works now
  }
}

This is not very consistent though - the following should also bind this, but it does not work as expected

class MyClass extends MyAbstractClass {
  foo: string = "ok";
  optional?: string;

  test = () => {
    this.get('foo'); // Doesn't work 
  }
  
}

Upvotes: 1

Related Questions