【问题标题】:Typescript - Class instance which implements generic typeTypescript - 实现泛型类型的类实例
【发布时间】:2020-06-11 21:01:45
【问题描述】:

我有一个使用通用接口创建类的函数。实例的属性由该泛型的参数设置,如下所示:

const ClassFactory = <T>() => {

    class MyClass {
        constructor(data: T) {
            for (const key in data) {
                if (!data.hasOwnProperty(key)) { continue; }
                (this as any)[key] = data[key];
            }
        }

        // other methods can be here
    }

    return MyClass;
}

const GeneratedClass = ClassFactory<{ id: number }>();

const myInstance = new GeneratedClass({ id: 1 });

console.log((myInstance as any).id); // logs 1

这按预期运行,但是有 2 个问题

  1. myInstance Typings 没有 T 的键 - 我希望 myInstance.id 是一个数字
  2. 我必须在构造函数中强制转换 this as any 以通过给定数据分配值

为了解决第一个问题,我尝试了从其他帖子中看到的各种方法,包括 class MyClass implements T,但它们都会导致相同的错误:A class can only implement an object type or intersection of object types with statically known members.ts(2422)。 我理解为什么会发生这种情况,但是由于在定义类时知道T,有没有办法让它工作?

如果我在 public data: T 属性中有数据,则 myInstance.data.id 的类型正确。所以我的问题是,这可以通过跳过.data 部分来完成吗?

提前致谢

【问题讨论】:

  • 为什么是javascript标签?
  • 试试return MyClass as { new(): T }。
  • @JonasWilms 感谢您的评论。通过使用return MyClass as { new(data: T): T };,它在上面的示例中可以正常工作,但是如果类中有任何方法,它就会失败。理想情况下,它只会覆盖new,而不是整个类。
  • 我认为,如果您回答自己的问题,您应该将其作为答案发布,而不是作为对问题的编辑。
  • @jcalz 是的,谢谢大家的时间和提示

标签: typescript generics


【解决方案1】:

受 Jonas Wilms 评论的启发,即使类有方法/静态,我也可以通过返回

return MyClass as (new (data: T) => T & InstanceType<typeof MyClass>) & typeof MyClass;

像这样,以下所有内容都按预期键入和运行

const myInstance = new GeneratedClass({ id: 1 });

console.log(myInstance.id, GeneratedClass.someStatic(), myInstance.someMethod());

但是,如果在类方法中使用new MyClass(),这将无法正常工作。

使其正常工作的解决方法是创建一个返回具有正确类型的实例的静态

        // inside the class
        public static build(data: T): T & InstanceType<typeof MyClass> {
            return new MyClass(data) as T & InstanceType<typeof MyClass>;
        }

然后以下是预期的

const myInstance = GeneratedClass.build({ id: 1 });

console.log(myInstance.id, GeneratedClass.someStatic(), myInstance.someMethod());

完整的工作示例

const ClassFactory = <T>() => {
    class MyClass {
        constructor(data: T) {
            for (const key in data) {
                if (!data.hasOwnProperty(key)) { continue; }
                (this as any)[key] = data[key];
            }
        }

        public static build(data: T): T & InstanceType<typeof MyClass> {
            return new MyClass(data) as T & InstanceType<typeof MyClass>;
        }

        public static someStatic() {
            return 2;
        }

        public someMethod() {
            return 3;
        }
    }

    return MyClass as (new (data: T) => T & InstanceType<typeof MyClass>) & typeof MyClass;
}

const GeneratedClass = ClassFactory<{ id: number }>();

const myInstance = new GeneratedClass({ id: 1 });

console.log(myInstance.id, GeneratedClass.someStatic(), myInstance.someMethod());

const myBuiltInstance = GeneratedClass.build({ id: 1 });

console.log(myBuiltInstance.id, GeneratedClass.someStatic(), myBuiltInstance.someMethod());

【讨论】:

    【解决方案2】:

    我刚刚遇到了这个问题,并且能够通过简单地放弃 new 并创建一个通用静态方法 Class.create() 来非常优雅地解决它,我在其中实例化并转换为正确的类型。

    interface MyGenericInterface<T = any> {
      getTheThing(): T
    }
    
    class MyClass implements MyGenericInterface {
      // Make constructor private to enforce contract
      private constructor(private thing: any) {}
    
      public getTheThing(): any {
        return this.thing
      }
    
      static create<TypeOfThing = any>(thing: TypeOfThing) {
        return new MyClass(thing) as MyGenericInterface<TypeOfThing>
      }
    }
    
    const stringyInstanceWrong = new MyClass('thing') // Error
    
    const stringyInstance = MyClass.create('thing')
    const stringThing: string = stringyInstance.getTheThing()
    
    const numberyInstance = MyClass.create(123)
    const numberyThingWrong: string = numberyInstance.getTheThing() // Error
    const numberyThing: number = numberyInstance.getTheThing() // Works!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多