推断/允许 typescript 中的扩展类型?

v64noz0r  于 2023-05-08  发布在  TypeScript
关注(0)|答案(1)|浏览(95)

有没有一种方法可以让示例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)
toiithl6

toiithl61#

你可以使on方法成为泛型,但是在调用它的时候你不必显式地传递这个泛型类型。将推断参数类型

static on3<T extends DomainEvent>(listener: (e: T) => void): void { }
...
DomainEvent.on3(handler1)

相关问题