microsoft / microsoft/TypeScript
Inference isn't working with constructor that contextually types 'this' with intersections of itself
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TL;DR: There should be no errors in the below example.
I am trying to model a library that takes an options bag for its constructor, and exposes those properties onto the instance that is eventually produced.
For example, if I wrote
let instance = new Component({
methods: {
hello() { }
world() {
this.hello();
}
}
});
I should be able to write instance.hello() or instance.world().
Additionally, since this in world will be bound to the instance, this.hello should be legal and well-typed in the above example.
However, I'm not able to come up with a version of this that works.
/**
* Ensures all properties have a `this` param of type `T`.
*/
interface ThisEnforced<T> {
[prop: string]: (this: T, ...args: any[]) => any;
}
interface ComponentOptions<Methods> {
methods?: Methods
}
interface Component<Methods extends ThisEnforced<Component<Methods> & Methods>> {
$methods: Methods;
}
interface ComponentStatic {
new <Methods extends ThisEnforced<Component<Methods> & Methods>>(options: ComponentOptions<Methods>):
// Returns...
Component<Methods> & Methods;
}
declare var Component: ComponentStatic;
let inst = new Component({
methods: {
hello() {
// ...
},
world() {
this.hello;
// ~~~~~
// Error: Property `hello` does not exist on this type.
}
},
});
inst.hello;
// ~~~~~
// Error: Property `hello` does not exist on this type.
In the above example, there should be no errors - however, it appears that no inferences are being drawn as a type argument for Methods, and both this.hello and inst.hello are causing errors.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the contextual-typing and constructor-inference example in the issue, focusing on the this type inside world and the inferred type of inst. Trace the TypeScript type-checking and generic-inference paths involved. Done means the example produces no errors, this.hello is accepted, and inst.hello is available with appropriate typing.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 25/100