mitt
mitt copied to clipboard
[TypeScript] TypeScript generic type
type TFsBaseToolEvent = {
startTool?: string;
cancelTool?: string;
};
interface IbaseTool<T extends TFsBaseToolEvent = TFsBaseToolEvent> {
test: (s: T) =>void;
event: Emitter<T>;
event2: Emitter<TFsBaseToolEvent>;
}
class BaseTool<T extends TFsBaseToolEvent = TFsBaseToolEvent> implements IbaseTool<T> {
event: Emitter<T>;
referenceEvent: Emitter<TFsBaseToolEvent>;
constructor() {
this.event = mitt();
this.referenceEvent = mitt<TFsBaseToolEvent>();
}
test (param: T) {
console.log(param.startTool);
this.event.emit('startTool'); // There is no inference type prompt.
this.referenceEvent.emit('startTool');
}
}
Line: 145
I have no idea what is causing this. Here's a simplified repro if anyone has ideas.
I tried fiddling around a bit with the code, but unfortunately came to no viable solution. But also would suggest that the issue has maybe to do with the way the emit-function in mitt is implemented. Added some lines of code and comments as I was testing. Maybe it has some use for anyone who wants to make an attempt: here
You can write this.event.emit('startTool', undefined);
You can write
this.event.emit('startTool', undefined);
Yes, you could write code like this; But the problem is, when you write code, there's no event type inference, it's not friendly.
I assume this is because the compiler can't know the type of <T> in event: Emitter<T>; and therefore can't know what keys would be valid events for this.event.emit('startTool'); because <T> may contain 'pauseTool' or any other key... or it may not.
If you want the mitt instance to respond to events from TFsBaseToolEvent then it needs to be defined with that type (event: Emitter<TFsBaseToolEvent>;)
Here's the explanation, it's not specifically a bug but more like a misconception of how the inferring works
https://github.com/microsoft/TypeScript/issues/48741#issuecomment-1101637791
Here's the explanation, it's not specifically a bug but more like a misconception of how the inferring works
Thank you, it was helpful.