mitt icon indicating copy to clipboard operation
mitt copied to clipboard

[TypeScript] TypeScript generic type

Open JaylanChen opened this issue 4 years ago • 6 comments

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');
  }
}

demo

Line: 145

JaylanChen avatar Jul 09 '21 09:07 JaylanChen

I have no idea what is causing this. Here's a simplified repro if anyone has ideas.

developit avatar Jan 31 '22 14:01 developit

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

reskes avatar Apr 10 '22 14:04 reskes

You can write this.event.emit('startTool', undefined);

iyegoroff avatar Apr 18 '22 21:04 iyegoroff

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.

JaylanChen avatar Apr 19 '22 03:04 JaylanChen

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>;)

sgoodgrove avatar Jul 03 '22 17:07 sgoodgrove

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

barelyhuman avatar Sep 23 '22 12:09 barelyhuman

Here's the explanation, it's not specifically a bug but more like a misconception of how the inferring works

microsoft/TypeScript#48741 (comment)

Thank you, it was helpful.

JaylanChen avatar Sep 25 '22 12:09 JaylanChen