Why generic parameter type with constraint cannot match pattern but using constraint type directly does?

huangapple go评论116阅读模式
英文:

Why generic parameter type with constraint cannot match pattern but using constraint type directly does?

问题

我正在构建一个类型化事件工具,并希望提供支持定制事件类型的功能。这个想法来自于bterlson/strict-event-emitter-types。在Demo中,我无法将通用类型添加到预定义事件中。我不知道如何修复它。有没有解决方法?

更新:演示

export type ListenerArgsType<T> = [T] extends [(...args: infer U) => any]
  ? U
  : [T] extends [void] ? [] : [T];

class TestEvent<TypedEventMap extends {'update': {id: number}}> {
    constructor() {
        // this.emit('update', { id: 1 }) 出错! 
        const events = new TestEvent<{ 'update': { id: number } }>()
        events.emit('update', {id: 1})
    }

    public emit<Type extends keyof TypedEventMap>(type: Type, ...data: ListenerArgsType<TypedEventMap[Type]>) {}
}
英文:

I am building a typed event utils and want to provide customized event types supporting. The idea comes from bterlson/strict-event-emitter-types. Within the Demo, I cannot add a generic type to extends predefined events. I dont known how to fix it. Any way to workaround?

Update: demo

export type ListenerArgsType&lt;T&gt; = [T] extends [(...args: infer U) =&gt; any]
  ? U
  : [T] extends [void] ? [] : [T];

class TestEvent&lt;TypedEventMap extends {&#39;update&#39;: {id: number}}&gt; {
    constructor() {
        // this.emit(&#39;update&#39;, { id: 1 }) Error! 
        const events = new TestEvent&lt;{ &#39;update&#39;: { id: number } }&gt;()
        events.emit(&#39;update&#39;, {id: 1})
    }

    public emit&lt;Type extends keyof TypedEventMap&gt;(type: Type, ...data: ListenerArgsType&lt;TypedEventMap[Type]&gt;) {}
}

答案1

得分: 0

作为 @rusev 的一方。我现在在函数体内进行投射。

英文:

As @rusev side. I am now casting inside the function body.

huangapple
  • 本文由 发表于 2020年1月3日 15:20:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574623.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定