创建实现接口的打字稿类

  • 本文关键字:实现 接口 创建 typescript
  • 更新时间 :
  • 英文 :


我想实现一个接口,但我很难获得正确的语法。

我想实现的接口

interface Test {
  [name : string] : (source : string) => void;
}

如果我理解正确,接口基本上是一个对象,字符串作为键,函数作为值。

任何帮助都非常感谢。

编辑:我收到几个错误,"接口实现不正确","缺少索引签名"等,

游乐场示例:链接

我没有实现接口,它来自 sdk

只需将索引签名添加到类中:

interface Test {
    [name: string]: (source: string) => void;
}
class TestClass implements Test {
    [name: string]: (source: string) => void; // Add this
    getLastName(source: string) {
        console.log("test"); 
    }
}

我不认为一个类可以实现这样的接口。

这更像是一个"类型化对象"接口。

您可以键入一个对象来指定它应该有一个字符串作为键,而函数应该接受一个字符串,但不返回任何值。

这样:

let myObj: Test = {
    test: (source: string) => { console.log('function returning void'); }
};

最新更新