简体   繁体   English

在TypeScript中针对接口键入非类

[英]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. 可以实例化RealRequestFactoryMockRequestFactory并将其作为依赖项注入到其他类中。 TypeScript however, allows us to declare anything as the interface type, so this can be done: 但是,TypeScript允许我们将任何内容声明为接口类型,因此可以这样做:

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 . 在这种情况下,我不需要实例化一个类,并且仍然可以将realRequestFactory注入为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? 是否有针对接口输入非类的共识?

这是一个单例,是的,单例被认为是反模式,因此该类更适合通过Dependencji注入容器进行测试和注入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM