为什么带约束的泛型参数类型不能匹配模式,而直接使用约束类型可以?
Why generic parameter type with constraint cannot match pattern but using constraint type directly does?
我正在构建类型化事件实用程序并希望提供自定义事件类型支持。这个想法来自 bterlson/strict-event-emitter-types. Within the 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 }) Error!
const events = new TestEvent<{ 'update': { id: number } }>()
events.emit('update', {id: 1})
}
public emit<Type extends keyof TypedEventMap>(type: Type, ...data: ListenerArgsType<TypedEventMap[Type]>) {}
}
作为@rusev 一方。我现在正在函数体内进行转换。
我正在构建类型化事件实用程序并希望提供自定义事件类型支持。这个想法来自 bterlson/strict-event-emitter-types. Within the 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 }) Error!
const events = new TestEvent<{ 'update': { id: number } }>()
events.emit('update', {id: 1})
}
public emit<Type extends keyof TypedEventMap>(type: Type, ...data: ListenerArgsType<TypedEventMap[Type]>) {}
}
作为@rusev 一方。我现在正在函数体内进行转换。