TypeScript 中静态方法的抽象方法版本 [英] Version of Abstract Methods for Static Methods in TypeScript

查看:29
本文介绍了TypeScript 中静态方法的抽象方法版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用打字稿创建数据模型范例.我将不同类型的数据存储在不同的地方(SQL、本地缓存).我想创建一个抽象类,其中包含任何类型的数据存储(创建、查找、更新、计数、销毁)所需的所有方法.通过这种方式,我可以扩展该类并针对不同类型的存储以不同的方式实现它,如果我缺少某个方法,编译器会警告我.然后,我将在描述数据模型的类中扩展这些实现之一.但是,我需要的一些方法(例如 find 和 create)是静态的.我知道打字稿不支持抽象静态方法.是否有类似于我可以使用的抽象方法的东西,以便编译器警告我缺少方法?

I am creating a data model paradigm with typescript. I store different types of data in different places (SQL, a local cache). I want to create an abstract class that contains all of the methods I would need for any type of data storage (create, find, update, count, destroy). This way I could extend that class and implement it differently for different types of storage and the compiler would warn me if I was missing a method. I would then extend one of those implementations in a class describing the data model. However, some of the methods I need (such as find and create) are static. I know typescript does not support abstract static methods. Is there something similar to abstract methods I could use so the compiler warns me about missing methods?

我还希望这些静态方法是通用的,并且类型与类相同.我知道这对于标准的泛型类没有意义.但是,由于这个类总是会被扩展并且永远不会被实例化,那么我可以在扩展它时输入泛型类,自动更新静态方法上的泛型类型吗?

I would also like these static methods to be generic and typed the same as the class. I know this makes no sense for a standard generic class. However, since this class will always be extended and never instantiated, could I type the generic class when I extend it, automatically updating the generic type on the static methods?

推荐答案

是否有类似于抽象方法的东西我可以使用,以便编译器警告我缺少方法

Is there something similar to abstract methods I could use so the compiler warns me about missing methods

不是内置的,所以你不会因为简单的错误

Not built in, so you will not get good errors by simply

// WILL NOT COMPILE. SAMPLE
class Foo {
    abstract static X() { } 
}

class Bar extends Foo { // Error here please
}

但是,您可以使用类型兼容性等技巧来确保:

However you can use tricks like type compatability to ensure:

interface FooAbstract {
    X(): any;
}
let _ensureAbstractMatch: FooAbstract;
class Foo {
}

class Bar extends Foo {
}
_ensureAbstractMatch = Bar; // Error missing method

示例实现:

interface FooAbstract {
    X(): any;
}
let _ensureAbstractMatch: FooAbstract;
class Foo {
}

class Bar extends Foo {
    static X() { }
}
_ensureAbstractMatch = Bar; // OKAY

这篇关于TypeScript 中静态方法的抽象方法版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆