Łukasz Ostrowski
Łukasz Ostrowski

Reputation: 1020

Typescript abstract class without implementation without errors

Is it possible to have an abstract class with strongly typed public methods but without implementation of them? I know it's an interface, but I can't use interface for Dependency Injection as a token in Angular. I need a structure for my other classes to implement. However, if I do something like this:

abstract class AbstractService { someMethod(): Observable<SomeType> {} }

Typescript will statically check it and error because it doesn't return a declared type.

I guess I can add some comments to the compiler code to prevent TS checking, but it seems to hacky.

Is there a way to prevent typescript this check and do it write? Big piece of my architecture is this service layer system for DI

Upvotes: 2

Views: 14135

Answers (2)

Alex Glinskiy
Alex Glinskiy

Reputation: 58

Here you go.

abstract class Base {
    public abstract hello(name: string): Promise<string>
    public abstract goodbye(name: string): Promise<string>
}

If you need to test your new class but you don't have all the methods implemented yet.

class Human extends Base {
    public hello(name: string) {
       // your implementation
    }
    public goodbye(name: string) {
        return 'Not implemented yet' as unknown as Promise<string>;
    }
}

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

You need to mark fields and methods that are not implemented as abstract

abstract class AbstractService {
    abstract someMethod(): Observable<SomeType>
}

This will also force implementing classes to actually implement the methods:

// Error: Non-abstract class 'Service' does not implement inherited abstract member 'someMethod' from class 'AbstractService'
class Service extends AbstractService{

}


 //ok, methods is implemented
class OkService extends AbstractService {
    someMethod() {
        throw new Error("Method not implemented.");
    }
}

You can read more about abstract classes here

Upvotes: 6

Related Questions