javascript - 将 Sinon 与 Typescript 和接口(interface)结合使用

标签 javascript interface typescript sinon

假设我有一个这样的类(class):

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

和这样的界面:

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

然后我想用Sinon来制作一个假用户:

user = sinon.createStubInstance(User);

这会产生如下错误:

Cannot convert type 'SinonStub' to type 'Employee'. Type 'Employee' has non-optional property 'firstName' which is not present on type 'SinonStub'.

Typescript 和诗乃似乎在一起并不愉快。

有没有办法创建一个实现 Typescript 接口(interface)的类的 SinonStub?

最佳答案

user 对象是否标记为“Employee”类型?如果是这样,这个错误就有意义。

sinon.createStubInstance(User) 将返回满足 SinonStub 的对象编译器警告的接口(interface)不符合 Employee 接口(interface)。

如果您不注释 user 的类型,则 typescript 会假设它是 SinonStub,并且不会遇到问题。如果您实际上没有对它进行注释,则该变量可能通过在其他地方使用而隐式地获取了注释。

如果这听起来不太对劲,那么您是否正在尝试完成一些未在问题中完成的事情?

关于javascript - 将 Sinon 与 Typescript 和接口(interface)结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36756244/

相关文章:

javascript - 在元素之间添加 div

javascript - 在javascript中如何在特定时间发送请求一些url(例如每天下午5点)

java - 在 UML 中,如果接口(interface)与类有关系,这种关系是否也适用于实现它的任何类?

node.js - Angular 2 : concurrent is not recognized as internal or external command

javascript - Angular 两次发送 http 请求

php - 如何在 jQuery 警报中显示 PHP 数组?

c# - 接口(interface)与单独项目中的类实现分开?

interface - 不是 Kotlin 中的意外覆盖

json - "resolveJsonModule"的用途?

javascript - TypeScript 报告对象可能是 'undefined' 而它不应该