Ton*_*oni 5 typescript typescript2.0
鉴于我有这个界面:
export class interface State {
default(): void;
}
Run Code Online (Sandbox Code Playgroud)
这个抽象类:
export abstract class BaseState implements State {}
Run Code Online (Sandbox Code Playgroud)
打字稿编译器告诉我“BaseState 错误地实现了接口 State” - 但这对我来说没有意义。如果抽象类实现了一个接口,则不应强制它实现它的所有方法,因为这也可以委托给子类。
我知道我能做到
export abstract class BaseState implements State {
abstract default(): void;
}
Run Code Online (Sandbox Code Playgroud)
但这绝对不是干的。那么,在 TypeScript 中存在这种行为有什么充分的理由吗?
由于 TypeScript 是结构类型的,因此添加语句的唯一原因implements是收到一条警告,提示您忘记从接口实现方法。
如果您不想收到有关此问题的警告,则可以简单地省略注释implements State。
示例...我正在使用Example接口来确保传递给我的对象usesExample是可接受的...我自始至终都获得类型安全,并且我不需要method在我的抽象类上放置 的抽象实现。
如果我想知道我是否忘记添加某些内容,我可以(可选)添加Example接口...但无论如何,使用的行都会执行此操作。SubExampleusesExample
interface Example {
method(): string;
}
abstract class BaseExample {
abstract foo(): string;
}
class SubExample extends BaseExample {
foo() {
return '';
}
method() {
return '';
}
}
function usesExample(example: Example) {
return example.method();
}
usesExample(new SubExample());
Run Code Online (Sandbox Code Playgroud)