Mohsen
Mohsen

Reputation: 65785

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

Upvotes: 24

Views: 22145

Answers (3)

Teodoro
Teodoro

Reputation: 1474

I just had the same problem and my solution was to build a json schema of my interface.
You can use an automated tool to built it for you by passing your custom interface like this:

typescript-json-schema "./myfile.ts" MyCustomType --strictNullChecks --noExtraProps --required --out=output.json

Then, you can use the extension jest-json-schema to check if your object matches your generated schema like this:

const mySchema = require('path/to/output.json')
expect(myStrangeObject).toMatchSchema(mySchema)

This worked like a charm for me.

(I'd recommend getting familiar with json schema keywords because those flags "--strictNullChecks --noExtraProps --required" makes a big difference when generating the schema depending on your interface definition)

Upvotes: 4

lazytype
lazytype

Reputation: 925

There are a number of different packages that would allow you to test this at "typecheck" time.

Here's an example using one that I wrote: https://tsplay.dev/oN94ow

Upvotes: 1

basarat
basarat

Reputation: 275917

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.

Upvotes: 11

Related Questions