Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write tests for typescript typing definition?

We have a Node.js lib, recently we added a type definitions for it.

But how could I test the type definition?

like image 680
zhaochy Avatar asked Mar 15 '18 09:03

zhaochy


2 Answers

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).

like image 83
Pasi Avatar answered Oct 21 '22 05:10

Pasi


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)

like image 43
Aleksi Avatar answered Oct 21 '22 05:10

Aleksi