We have a Node.js lib, recently we added a type definitions for it.
But how could I test the type definition?
The tests in DefinitelyTyped are files that are supposed to type-check correctly. So the test exercises different parts of the API, and it's run through the compiler (but the generated JavaScript code is not actually executed). See, for example, tests for @types/express.
For your own project, I guess you'd write a similar test file yourself, and compile it as part of your build (if it compiles, then the test succeeds). Of course, if you already have existing TypeScript code using those type definitions, that might be sufficient test.
Typings-checker is a proof-of-concept that also allows testing failures (incorrectly typed code should not compile).
Microsoft's dtslint
is a handy tool for testing type declarations. As the name suggests its a static analysis tool that doesn't run your test files but only type-checks them. You can additionally supplement tests with comment-based assertions that the tool evaluates:
import { f } from "my-lib"; // f is(n: number) => void
// $ExpectType void
f(1);
// Can also write the assertion on the same line.
f(2); // $ExpectType void
// $ExpectError
f("one");
tsd
is another tool with similar assertions:
import {expectType} from 'tsd';
import concat from '.';
expectType<string>(concat('foo', 'bar'));
expectType<string>(concat(1, 2));
Also as of Typescript 3.9 you can use the built-in // @ts-expect-error
comment:
When a line is prefixed with a // @ts-expect-error comment, TypeScript will suppress that error from being reported; but if there’s no error, TypeScript will report that // @ts-expect-error wasn’t necessary. (source)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With