有没有一种方法可以让示例1工作,而不需要像示例2那样传递<UserDomainEvent>
?
目标是使使用更简单。
TS沙盒
abstract class DomainEvent {
static on1(listener: (e: DomainEvent) => void): void { }
static on2(listener: <T extends DomainEvent>(e: T) => void): void { }
}
export class UserDomainEvent extends DomainEvent {
public readonly userId: number = 1;
}
// Usage
// Is there a way to make this work,
// without the need to pass type specifics like in example 2?
const handler = (e: UserDomainEvent): void => { }
DomainEvent.on1(handler) // error
const handler2 = <UserDomainEvent>(e: UserDomainEvent): void => { }
DomainEvent.on2(handler2)
1条答案
按热度按时间toiithl61#
你可以使
on
方法成为泛型,但是在调用它的时候你不必显式地传递这个泛型类型。将推断参数类型