gpt4 book ai didi

Typescript - 为什么没有相应地强制实现接口(interface)

转载 作者:行者123 更新时间:2023-12-03 23:48:08 27 4
gpt4 key购买 nike

我想知道为什么实现两次相同的通用接口(interface)但使用不同的参数并不能在派生类中强制执行正确的签名。泛型参数的类型被省略。

请看样例:

interface IEvent { id: number; }
interface IHandle<T> {
handle(event: T): void;
}

class EmailSentEvent implements IEvent {
constructor(public id: number, public address: string) {}
}

class UserRegisteredEvent implements IEvent {
constructor(public id: number) {}
}

class MailHandlerState implements
IHandle<EmailSentEvent>,
IHandle<UserRegisteredEvent>
{
// One implementation is enough to satisfy both interfaces
handle = (event: EmailSentEvent): void => {

};
}

Sandbox

有没有办法强制执行两个泛型参数?谢谢!

最佳答案

TLDR:

要完成这项工作,请更改 方法符号

interface IHandle<T> {
handle(event: T): void;
}

函数类型为 的属性
interface IHandle<T> {
handle: (event: T) => void;
}

Playground

** 在这种特定情况下,实现仍然可以使用方法语法

事实证明这是按预期工作的:

--strictFunctionTypes mode in which function type parameter positions are checked contravariantly instead of bivariantly. The stricter checking applies to all function types, except those originating in method or construcor declarations. Methods are excluded specifically to ensure generic classes and interfaces (such as Array) continue to mostly relate covariantly. The impact of strictly checking methods would be a much bigger breaking change as a large number of generic types would become invariant (even so, we may continue to explore this stricter mode)



Source

也在 handbook

关于Typescript - 为什么没有相应地强制实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61269388/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com