Search code examples
typescriptspread-syntax

How to get around the error when using Spread to make an object copy where the object class has abstract methods?


In the following code, I have an abstract class, which requires extended classes to implement an abstract method. When using "spread" syntax, it complains about the implementation of the abstract method is missing.

abstract class Test {
    abstract func(): void;
}

class Test1 extends Test {
    func(): void {}
}

function funcTest(): void {
    const test1: Test = new Test1();
    const test: Test = {...test1};
}

How do you use spread to make a copy of an object of class with abstract methods? If can't, is there a way around it?

Here is the example code: https://stackblitz.com/edit/typescript-zuryyw


Solution

  • By definition you can't create an instance of an abstract class - no matter which mechanism you use.


    Spread will create a new object, it won't be of type Test, so the assignment to a variable of type Test will be based on it having the same properties and methods.

    You can accomplish that when you remove func from Test, but you can't when its there because the object created by spread doesn't have all the properties and methods of Test.