【问题标题】:Interface signature not matching接口签名不匹配
【发布时间】:2023-09-25 16:07:01
【问题描述】:

我不知道为什么会出现错误:

export interface IGrid {
    (gridCell: GridCell): boolean
}

在我的课堂上

foo(gridCell: GridCell): boolean {
    return true;
}

错误:

类“X”错误地实现了接口“IGrid”。输入“X” 不提供签名'(gridCell: GridCell): boolean'的匹配项

更新:

我在接口的 gridFormat 签名中添加了一个参数。

export interface IGrid {
    gridFormat(gridCell: GridCell, x: number): boolean
}

类:

gridFormat(gridCell: GridCell): boolean {
    return true;
}

现在的问题是没有错误,该类没有实现具有x: number 参数的功能。我怎样才能让接口正确地要求该功能。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您的IGrid 接口是function interface,这意味着该接口描述了一个函数。你可以这样实现它:

    let yourFunc: IGrid = (gridCell: GridCell): boolean => {
        return true;
    };
    

    如果你想在一个类中实现它,你的接口可能应该声明一个带有函数成员的class type interface

    export interface IGrid {
        foo(gridCell: GridCell): boolean
    }
    
    class Grid implements IGrid {
        foo(gridCell: GridCell): boolean {
            return true;
        }
    }
    

    回复:为什么实现缺少接口中定义的参数时没有错误:

    这是设计使然。见this issueTypeScript FAQ

    【讨论】:

    • 好的,这可行,但我仍然无法让我的界面按我想要的方式工作。我已经更新了这个问题。签名不匹配但没有错误。
    • @el_pup_le 这实际上是设计使然。见thisthis
    • 谢谢,这很令人沮丧。我看你是C#人,你知道C#是不是这样设计的吗?
    • @el_pup_le 否。C# 支持方法重载,所以这样的事情会在 C# 中引发错误。 JavaScript(TypeScript 编译成的)没有方法重载。
    • 是否可以强制类具有完全匹配接口函数签名的函数?不允许使用可选参数。