typescript 抽象类静态方法未强制执行

标签 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;
}

即使 CoreInterface() 成员在 Test 类中丢失,TypeScript 也不会提示。为什么是这样?

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

最佳答案

根据您的评论,您可以通过以下方式实现您的目标:

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' incorrectly implements interface 'Config'.
Property 'NAME' is missing in type 'Test'.

如果你注释掉静态的 CoreInterface 你会得到这个错误:

Type 'typeof Test' is not assignable to type 'ConfigConstructor'.
Property 'CoreInterface' is missing in type 'typeof Test'.


原始答案

静态成员/方法不适用于继承(这通常适用于 OO 而不是特定于 typescript )因为(正如@JBNizet 评论的那样)所有静态属性都属于类本身而不属于实例。

写在Wikipedia article :

A static method can be invoked even if no instances of the class exist yet. Static methods are called "static" because they are resolved at compile time based on the class they are called on and not dynamically as in the case with instance methods, which are resolved polymorphically based on the runtime type of the object. Therefore, static methods cannot be overridden

同时检查这个线程: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 )

关于 typescript 抽象类静态方法未强制执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43723313/

相关文章:

java - 接口(interface)的意图与具有抽象方法的抽象类有何不同?

c# - IList<T> 和 IReadOnlyList<T>

swift - 如何在 Swift 中初始化 Struct 中的变量一次

java - 在此接口(interface)定义中,尖括号是什么意思?

c - 什么时候在全局变量前使用 static 关键字?

php - 从实例调用静态函数

gruntjs - Gruntfile.js 中的智能感知

angular - Websocket onmessage 事件只触发一次

javascript - Angular 2-datatable 中的 Angular 2 搜索过滤器查询 - 类型 'first_name' 上不存在属性 '{}'

javascript - 在 Fetch 中返回 Promise.Reject()