我有一些接口及其实现的定义。必须在每个实现类上声明许多方法。
我认为这是一个单调乏味和多余的定义。是否只是缺乏时间来实现此功能,或者为什么要强制执行环境实现定义?或者有什么我错过了吗?
更新
我现在不喜欢我的问题,它是从一个确定接口成员已实现的人的角度编写的,因为图书馆老板说的。但是,如果我决定创建自己的接口到其他人的库,我最好强制指定每个实施成员作为完整性检查。
答案 0 :(得分:3)
假设您没有写出界面成员:
class Base { }
class Derived extends Base { }
interface Foo {
method(t: number): Base;
}
declare class FooImpl1 implements Foo {
// Empty
}
declare class FooImpl2 implements Foo {
public method(): Derived;
}
FooImpl2
是否尝试声明method
的额外重载,或FooImpl2
使用签名来实现method
,该签名占用较少的参数并返回更多派生类型?两者都是有效的解释。你必须为这样的各种情况制定规则,以便程序员可以指定它们的实际含义,使语言更难以预测。
答案 1 :(得分:1)
您不应该为环境声明提供任何实现。
例如,接口只会描述没有实现的类型:
interface MyInterface {
property: string;
method(input: number): void;
}
同样适用于类或模块的环境声明:
declare class MyClass {
property: string;
method(input: number): void;
}
如果要为实现和接口的类表示环境声明,可以使用以下快捷方式:
interface MyInterface {
property: string;
method(input: number): void;
}
declare var MyClass: MyInterface;