Write tests for your type definitions

Stefan Alfbo - Apr 15 - - Dev Community

Say hello to the tsd npm package, the tool that lets you write tests for your type definitions.

Lets explore the package by first adding it to an existing project.

npm install --save-dev tsd
Enter fullscreen mode Exit fullscreen mode

Then we begin with a simple example by adding this TypeScript file tsd-examples.ts.

export const asString = (n: number) => n.toString()
Enter fullscreen mode Exit fullscreen mode

Now we can add a happy path test in a file called tsd-examples.test-d.ts, note the naming convention here with the .test-d.ts.

import { expectType } from 'tsd'
import { asString } from './tsd-examples'

expectType<string>(asString(42))
Enter fullscreen mode Exit fullscreen mode

Here we test that the function asString is typed to return a value of the type string. Run the test by executing following command in the terminal:

npx tsd -t ./tsd-examples.test-d.ts
Enter fullscreen mode Exit fullscreen mode

If there is no output then everything is ok, ðŸŸĒ, however if you change the test like this instead.

import { expectType } from 'tsd';
import { asString } from './tsd-examples';

expectType<string>(asString("42"))
Enter fullscreen mode Exit fullscreen mode

Notice the change for the input parameter, 42 to "42". Execute the test again with npx tsd -t ./tsd-examples.test-d.ts.

test error

We could update our test like this if we want to cover that case too.

import { expectError, expectType } from 'tsd';
import { asString } from './tsd-examples';

expectType<string>(asString(42))
expectError<string>(asString("42"))
Enter fullscreen mode Exit fullscreen mode

Here we import the expectError so that we can verify the type error with the string "42". Now when we rerun the tsd command it once again passes all the tests.

So far it has been pretty straight forward and perhaps these test do not bring much value over the linting tool available in your IDE.

However types in TypeScript can be much more complex, the issue TypeScripts Type System is Turing Complete might give a hint about this.

So this example just scratch the surface, If you want to see a more advance use of tsd, then take a look at, TypeLang, which implements an interpreter with TypeScript type annotations.

Happy TypeScripting!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .