【问题标题】:Typescript: Work with Child Class in static method打字稿:在静态方法中使用子类
【发布时间】:2021-01-13 23:37:42
【问题描述】:

在TypeScript(我使用Playground,版本4.13)中,当我从一个类继承时,父类的static方法内的this似乎是指继承类:

class Parent{
    static ID = 0
    public id: number

    static create(){
        return new this(this.ID)
    }

    constructor(id: number){
        this.id = id
    }
}

class Child extends Parent{
    static ID = 1
}

let child = Child.create()
console.log(child.id)  // 1

但是,当我想根据子类的类型定义一些行为时,我遇到了问题:

class Parent{
    static create(data: object){
        let instance = new this
        for (let [key, value] of Object.entries(data)){
            this[key] = value
        }
        return instance
    }
}

class Child extends Parent{
    id: number | null = null
}

let child = Child.create({id: 1})
console.log(child.id)

这给了我

元素隐含地有一个'any'类型,因为表达式类型为'string |号码 |符号'不能用于索引类型'typeof Parent'。在“typeof Parent”类型上找不到带有“string”类型参数的索引签名。

我试图通过将key 类型转换为子类的键来解决这个问题:

class Parent{
    static create(data: object){
        let instance = new this
        for (let [key, value] of Object.entries(data)){
            this[key as keyof this] = value
        }
        return instance
    }
}

class Child extends Parent{
    id: number | null = null
}

let child = Child.create({id: 1})
console.log(child.id)

但这是被禁止的。我明白了

“this”类型仅在类或接口的非静态成员中可用

另外,我得到(在所有情况下)

“父”类型上不存在属性“id”。

如何解决我的问题 - 从一个对象(我在实际场景中从 API 接收)动态填充子类的属性?

【问题讨论】:

  • 我建议你看看 js 方法:bind()、call()、apply() 以及“this”关键字在 JS 中的工作原理。

标签: typescript oop keyof


【解决方案1】:

您可以通过指定与类本身对应的this 参数来完成此操作。在静态方法中,this 指的是类本身。

static create<T extends Parent>(this: new (...args: any[]) => T, data: object) {...} 

这里发生的事情是我们说this 类型,它将引用包含该方法的对象,在这种情况下,无论调用create 的任何类对象,都可以返回实例的子类型类的类型。这是通过类型参数T 实现的,并且类对象将具有返回T 的构造签名,从而捕获任何派生类的实例类型。

这是完整的工作代码:

class Parent {
    static create<T extends Parent>(this: new (...args: any[]) => T, data: object) {
        let instance = new this;
        for (let [key, value] of Object.entries(data)) {
            instance[key as keyof T] = value;
        }
        return instance;
    }
}

class Child extends Parent {
    id: number | null = null;
}

let child = Child.create({ id: 1 });
console.log(child.id);

Playground Link

由于我们已经通过T 捕获了派生实例类型,我们可以通过如下调整create 来进一步细化create 方法以提高类型安全性:

static create<T extends Parent>(this: new (...args: any[]) => T, data: Partial<T>) {...}

这可以防止我们在提供智能感知的同时传递任意属性,从而将任意属性分配给由create 方法创建的对象。

完整代码:

class Parent {
    static create<T extends Parent>(this: new (...args: any[]) => T, data: Partial<T>) {
        let instance = new this;
        for (let [key, value] of Object.entries(data)) {
            const k = key as keyof T;
            instance[k] = value as T[typeof k];
        }
        return instance;
    }
}

class Child extends Parent {
    id: number | null = null;
}

let child = Child.create({ id: 1 });
console.log(child.id);

Playground Link

【讨论】:

  • 抱歉这个后续问题:在我原来的问题中,Parent 上还有一个静态变量。当我现在在create 中访问这个类成员时,我得到 Property does not exist on type 'new (...args: any[]) => T' 我不知道如何解决这个问题。我希望该属性存在于 T 上,因为 T 扩展了 Parent。但它不起作用......
  • 您必须执行类似this: {[P in keyof typeof Parent]: typeof Parent[P]} &amp; (new (...args: any[]) =&gt; T) 的操作。一句忠告。您似乎一直对类的静态和实例方面感到困惑。静态成员永远不能通过构造类产生的类型获得。就个人而言,我认为使用大量静态成员是一种反模式。只导出工厂函数并使用闭包更简单、更惯用
  • 感谢您的建议。我来自 Python,在那里我习惯于与类成员一起工作,这些成员可以由类及其实例来处理。所以,我想您的想法可能是正确的 - 感谢您为我指明正确的方向。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 2019-01-24
  • 2020-04-20
相关资源
最近更新 更多