测试对象是否符合TypeScript中的接口

Moh*_*sen 3 testing typescript

如果我有一个普通的JavaScript对象和一个TypeScript接口,我怎样才能编写一个断言符合我接口的对象的测试?

interface Person {
  name: string
  age?: number
}

describe('Person interface check', () => {
  it ('should conform to "Person" interface', () => {
     let obj1 = {name: "Mohsen"};
     let obj2 = {name: "Hommer", age: 40};

     expect(obj1) // ????
  });
});
Run Code Online (Sandbox Code Playgroud)

编辑:我不想做深刻的断言,例如expect(obj1.name).to.be.a.string

bas*_*rat 5

断言符合我界面的对象

你必须手动完成:

expect(typeof object.name).to.eql("string");
// so on 
Run Code Online (Sandbox Code Playgroud)

更新:编写代码为您做深度断言

由于在生成的JS中删除TypeScript看到的类型信息,因此您无法访问js中的类型信息.但是,您可以编写代码来获取代码的TS视图(使用typescript语言服务)并生成为您执行这些深层断言的JS代码.