简体   繁体   English

使用Sinon与Typescript和接口

[英]Using Sinon with Typescript and interfaces

Say I have a class like this: 说我有这样一个类:

export class User implements Employee {
    lanId: string;
    firstName: string;
    lastName: string;
}

and an interface like this: 和这样的界面:

export interface Employee {
     firstName: string;
     lastName: string;
}

I then want to use Sinon to make a fake user: 然后,我想使用Sinon来制作假用户:

user = sinon.createStubInstance(User);

This gives an error like this: 这给出了这样的错误:

Cannot convert type 'SinonStub' to type 'Employee'. 无法将类型'SinonStub'转换为'Employee'类型。 Type 'Employee' has non-optional property 'firstName' which is not present on type 'SinonStub'. 类型'Employee'具有非可选属性'firstName',它不存在于'SinonStub'类型上。

It seems like Typescript and Sinon are unhappy together. 这似乎是打字稿及兴农不高兴起来。

Is there a way to create a SinonStub of a class that implements a Typescript interface? 有没有办法创建一个实现Typescript接口的类的SinonStub?

Is the user object marked as being of type 'Employee'? user对象是否标记为“Employee”类型? If so, this error makes sense. 如果是这样,这个错误是有道理的。

sinon.createStubInstance(User) will return an object meeting the SinonStub interface which as the compiler warns is not compliant with the Employee interface. sinon.createStubInstance(User)将返回一个符合SinonStub接口的对象,编译器警告该对象不符合Employee接口。

If you don't annotate the type of user typescript moves forward assuming it is a SinonStub and you won't run into the issue. 如果你没有注释user打字稿的类型向前推进,假设它是一个SinonStub,你就不会遇到这个问题。 If you haven't actually annotated it, it's possible the variable picked up the annotation implicitly through usage elsewhere. 如果您实际上没有注释它,则变量可能通过其他地方的使用隐式地获取注释。

If that sounds off, is there something you're trying to accomplish that isn't in the question? 如果这听起来不合适,那么你想要完成的事情是不是在问题中?

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

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