在TypeScript中针对接口键入非类

时间:2019-03-13 11:16:39

标签: typescript

我的应用程序利用工厂帮手来配置各种对象。每个工厂都实现一个接口,可以对其进行模拟以辅助测试。传统上,每个工厂都是实现该接口的类:

const displayExtraUserInfo = (params) => {
            document.getElementById("btn-birthdate").addEventListener("click", ()=> {
                displayBirthdate(params)
            })

           document.getElementById("btn-phone").addEventListener("click", () => {
                displayPhone(params)
            })
            document.getElementById("btn-address").addEventListener("click", () => {
                displayAddress(params)
            })

        }
可以实例化

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并将其作为依赖项注入到其他类中。但是,TypeScript允许我们将任何内容声明为接口类型,因此可以做到这一点:

MockRequestFactory

在这种情况下,我不需要实例化一个类,并且仍然可以将const realRequestFactory: IRequestFactory = { create(event: AWSLambda.APIGatewayProxyEvent): Request { return new Request(event) } } 注入为类型realRequestFactory的依赖项。这种方法似乎更简单,但是我不确定它是否会被视为最佳实践,因为它有点像单例。

是否有针对接口输入非类的共识?

1 个答案:

答案 0 :(得分:1)

这是一个单例,是的,单例是considered an anti-pattern,因此该类更适合通过Dependencji注入容器进行测试和注入