typescript - Typescript 中的类方法

标签 typescript inheritance class-method

我希望能够在 Typescript 中使用基于类的方法 - 即在基类上定义的方法,当在子类上调用时,可以访问调用它的子类。这种行为在 Python 中是可能的,但据我所知,在 Typescript 中没有对应的行为。在 Typescript 中复制它的最佳方法是什么?

示例(在 Python 中):

这个例子(用 Python 编写)演示了我可能想用它做的事情。

# Base class
class Model:
    objects = []

    def __init__(self, objId):
        self.objId = objId

        Model.objects.append(self)

    @classmethod
    def getById(cls, objId):
        # Method can access subclass using "cls" parameter
        objects = [obj for obj in cls.objects if obj.objId == objId]
        if len(objects) > 0:
            return objects[0]
        else:
            print("error")

# Subclass
class Foo(Model):
    def __init__(self, objId, name):
        self.objId = objId
        self.name = name

        Foo.objects.append(self)

Foo(1, "foo")
Foo(3, "bar")

# Call method on subclass
foo = Foo.getById(1)
bar = Foo.getById(3)

print(foo.name)  # outputs "foo"
print(bar.name)  # outputs "bar"

Foo.getById(2)  # outputs "error"

typescript (不工作):

此示例显示了 typescript 中的粗略等效项,但由于缺少类方法而无法正常工作。

class Model {
    static objects: Model[]

    id: number

    constructor (id) {
        this.id = id

        Model.objects.push(this);
    }

    // Here "cls" should refer to the class on which this method is called
    static getById (id): cls {
        let item = cls.objects.find(obj => obj.id == id);
        if (item === undefined) {
            console.log("error");
        } else {
            return item;
        }
    }
}

class Foo extends Model {
    name: string

    constructor (id, name) {
        super(id);

        this.name = name

        Foo.objects.push(this);
    }
}


new Foo(1, "foo");
new Foo(3, "bar");

// Here cls === Foo
let foo = Foo.getById(1);
let bar = Foo.getById(3);

console.log(foo.name);
console.log(bar.name);

Foo.getById(2)

很明显,这对于单个类来说很容易做到,但我想不出一种方法来将这样的方法用于多个类,而无需在每个类上重新声明它。

附带问题:

有没有办法在每个子类上拥有一个“对象”静态属性,每个子类都输入到它们的子类中,而无需手动重新声明它。

class Model {
    static objects: Model[]

class Foo extends Model {
    static objects: Foo[]

class Bar extends Model {
    static objects: Bar[]

本质上,我想要这种行为,但不必在每个子类上单独声明“对象”属性。有什么办法吗?

最佳答案

静态方法的 this 上下文是调用它的类。您可以覆盖 getByIdthis 类型,以声明 getById 可以在 Model 的任何子类上调用(即, 具有构建 Model 子类型的构造签名的任何对象)并返回该类的实例类型。下面是示例代码,假设所有子类的所有对象都存储在单个 Model.objects 数组中:

class Model {
    static objects: Model[]

    id: number

    constructor (id) {
        this.id = id

        Model.objects.push(this);
    }

    static getById<M extends Model>(
        this: { new(...args: any[]): M }, id): M {
        let item = Model.objects.find(obj => obj.id == id);
        if (item === undefined) {
            console.log("error");
        } else {
            return <M>item;
        }
    }
}

请注意,这是不合理的,因为有人可以使用对应于 Bar 而不是 Foo 的 ID 调用 Foo.getById

如果你想为每个子类创建一个单独的 objects 数组,你需要在每个子类中手动初始化数组(没有办法自动完成),更改 Model 构造函数插入当前类的 objects 数组(声明后可以引用为 this.constructor),然后更改 getById 在声明它必须存在之后使用 this.objects

class Model {
    static objects: Model[]
    "constructor": {
        // This implementation is slightly unsound: the element type
        // is actually the instance type of the constructor.  At least
        // the interface provided is safe.
        objects: Model[]
    };

    id: number

    constructor (id) {
        this.id = id

        this.constructor.objects.push(this);
    }

    static getById<M extends Model>(
        this: { new(...args: any[]): M, objects: M[] }, id): M {
        let item = this.objects.find(obj => obj.id == id);
        if (item === undefined) {
            console.log("error");
        } else {
            return item;
        }
    }
}

关于typescript - Typescript 中的类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52895990/

相关文章:

visual-studio - 我可以使用 Visual Studio Community 2015 通过 TypeScript 进行开发吗?

javascript - 如何通过 JS 中的 WebPack 包提供全局 TypeScript 类

java - 使用接口(interface)在2个java类之间进行通信

objective-c - 如何在 Swift 类中从 Objective C 调用单例类方法?

python - 适用于类方法和实例方法的装饰器

javascript - 如何使用 typescript 编写 vuex 存储?

node.js - 当 "Don' t do it 不是一个选项时,我如何将 Typescript 命名空间与外部模块混合使用?

WCF MessageContract 继承

java - 为子类设置父类(super class)属性

java - 子类的ArrayList不能赋值给父类(super class)的ArrayList