How to unit test model interfaces in typescript?

For future users with a similar question, I've come up with the following system for testing interfaces (which I only use with particularly quirky interfaces, like those I've autogenerated). It's absolutely a workaround, but it does fail my builds if the interface isn't appropriately specified.

First, in the "test", cast an object with the expected fields and types into the interface. For instance,

interface MyInterface = { 
  id: number;
  createTime: Date;
}

test("MyInterface should have appropriate fields and types", () => {
  ({
    id: 3,
    createTime: new Date(),
  } as MyInterface);
})

Then, I added a build step for compiling the TypeScript, which will error if MyInterface is changed.

tsc --noEmit

Again: my tests have no assertions in them, so they're not a real unit test, and this is a workaround. But this process has alerted me to problems a few times, so it serves the purpose.


You can't. There is no code to cover here: nothing is executable.

And interfaces only exist at compile-time. They don't exist at runtime.