Ben Guest
Ben Guest

Reputation: 1568

Typing non-classes against interfaces in TypeScript

My application makes use of factory helpers for provisioning various objects. Each factory implements an interface, which allows it to be mocked to aid testing. Traditionally, each factory would be a class that implements the interface:

interface IRequestFactory {
    create(event: AWSLambda.APIGatewayProxyEvent): IRequest
}

class RealRequestFactory implements IRequestFactory {
    public create(event: AWSLambda.APIGatewayProxyEvent): RealRequest {
        return new RealRequest(event)
    }
}

class MockRequestFactory implements IRequestFactory {
    public create(event: AWSLambda.APIGatewayProxyEvent): MockRequest {
        return new MockRequest(event)
    }
}

RealRequestFactory, or MockRequestFactory can be instantiated and injected into other classes as a dependency. TypeScript however, allows us to declare anything as the interface type, so this can be done:

const realRequestFactory: IRequestFactory = {
    create(event: AWSLambda.APIGatewayProxyEvent): Request {
        return new Request(event)
    }
}

In this case, I don't need to instantiate a class, and can still inject realRequestFactory as a dependency of type IRequestFactory. This approach seems simpler, but I'm not sure it would be considered best practice because it feels a bit like a singleton.

Is there a consensus for typing non-classes against interfaces?

Upvotes: 0

Views: 38

Answers (1)

wookieb
wookieb

Reputation: 4489

It's a singleton and yes singleton is considered an anti-pattern so class is better for testing and injection via Dependencji Injection Container

Upvotes: 1

Related Questions