假设我有一个包含许多方法的类,但我确信它们的签名匹配。
有没有可能只描述这个类的接口(interface),而不描述里面这个类的具体方法呢?喜欢这里:
interface IController {
(input: string): number // any method without reference to its name
}
class Controller implements IController {
method1(input: string): number { ...do something }
method2(input: string): number { ...do something }
...
}
还是不可能的?
最佳答案
具有索引签名的选项(如@fk82 在他的回答中概述的那样)会产生强制您向类添加索引签名的不良后果。这意味着您的类可以通过任意字符串进行索引,这可能不是您想要的。
如果您的目标只是强制实现类仅具有具有给定签名的方法,更好的选择是使用映射类型:
type IController<K extends PropertyKey> = {
[P in K]: (input: string) => number;
}
class Controller implements IController<keyof Controller> {
method1(input: string): number { return input.length; }
method2(input: string): number { return input === '' ? 0 : 1; }
}
let a = new Controller();
a['aa'] // not allowwed under no implicit any
这有额外的好处,允许类有一些不符合签名的方法,如果需要的话,但是以明确的方式:
class Controller implements IController<Exclude<keyof Controller, 'special'>> {
method1(input: string): number { return input.length; }
method2(input: string): number { return input === '' ? 0 : 1; }
special() { }
}
关于javascript - 仅使用没有名称的方法签名声明类的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53924151/