Typescript抽象类静态方法没有强制执行

时间:2017-05-01 17:17:26

标签: typescript interface static abstract-class static-typing

我在TypeScript中有这个简单的代码:

abstract class Config {
    readonly NAME: string;
    readonly TITLE: string;

    static CoreInterface: () => any
}

class Test implements Config {
    readonly NAME: string;
    readonly TITLE: string;
}

即使 Test 类中缺少 CoreInterface()成员,TypeScript也不会抱怨。为什么是这样?

我需要每个派生类在 CoreInterface()静态函数中提供有关自身的一些元数据。我知道我可以扩展Config类并让每个子类提供自己的 CoreInterface()实现,但我不希望子类自动继承COnfig类的任何成员。这就是为什么我使用" implements"而不是"延伸"

1 个答案:

答案 0 :(得分:7)

根据您的评论,您可以了解如何实现您的目标:

interface ConfigConstructor {
    CoreInterface: () => any;
    new (): Config;
}

interface Config {
    readonly NAME: string;
    readonly TITLE: string;
}

const Test: ConfigConstructor = class Test implements Config {
    readonly NAME: string;
    readonly TITLE: string;

    static CoreInterface = function (): any { return "something"; }
}

code in playground

如果你注释掉其中一个成员(即:NAME),你会收到此错误:

  

Class' Test'错误地实现了界面'配置'   物业' NAME'类型'测试'

中缺少

如果您注释掉静态CoreInterface,则会收到此错误:

  

Type' typeof Test'不能分配给类型' ConfigConstructor'。
  Property' CoreInterface'类型' typeof Test'。

中缺少

原始答案

静态成员/方法不使用继承(一般来说对OO是真的而不是打字稿特有的)因为(如@JBNizet所评论的)所有静态属性都属于类本身而不是实例。

正如Wikipedia article所述:

  

即使没有该类的实例,也可以调用静态方法   然而。静态方法被称为"静态"因为他们已经解决了   根据调用它们的类而不是动态编译时间   与实例方法的情况一样,已解决   多态地基于对象的运行时类型。因此,   静态方法无法覆盖

同时检查此主题:Why aren't static methods considered good OO practice?

至于你想要实现的目标,在扩展类时不能实现静态方法会导致编译错误,但是你可能会遇到运行时错误:

class A {
    static fn() {
        throw new Error("not implemented!");
    }
}

class B extends A {
    static fn() {
        console.log("B.fn");
    }
}

class C extends A { }

B.fn(); // ok
C.fn(); // error: not implemented!

code in playground