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
Then we begin with a simple example by adding this TypeScript file tsd-examples.ts
.
export const asString = (n: number) => n.toString()
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))
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
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"))
Notice the change for the input parameter, 42
to "42"
. Execute the test again with npx tsd -t ./tsd-examples.test-d.ts
.
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"))
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!