Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if an object conforms to an interface in TypeScript

If I have a plain-old JavaScript object and a TypeScript interface, how can I write a test that asserts object conforming to my interface?

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) // ????
  });
});

EDIT: I don't want to do deep assertion, eg expect(obj1.name).to.be.a.string

like image 769
Mohsen Avatar asked Jun 15 '15 23:06

Mohsen


1 Answers

asserts object conforming to my interface

You have to do it manually:

expect(typeof object.name).to.eql("string");
// so on 

Update : Writing code to do the deep assertion for you

Since the type information TypeScript sees is removed in the generated JS you don't have access to the type information in js. However you can write code to take the TS view of the code (using the typescript language service) and generate the JS code that does these deep assertions for you.

like image 165
basarat Avatar answered Oct 12 '22 11:10

basarat