• Stars
    star
    2,116
  • Rank 21,792 (Top 0.5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Check TypeScript type definitions

tsd CI

Check TypeScript type definitions

Install

npm install --save-dev tsd

Overview

This tool lets you write tests for your type definitions (i.e. your .d.ts files) by creating files with the .test-d.ts extension.

These .test-d.ts files will not be executed, and not even compiled in the standard way. Instead, these files will be parsed for special constructs such as expectError<Foo>(bar) and then statically analyzed against your type definitions.

The tsd CLI will search for the main .d.ts file in the current or specified directory, and test it with any .test-d.ts files in either the same directory or a test sub-directory (default: test-d):

[npx] tsd [path]

Use tsd --help for usage information. See Order of Operations for more details on how tsd finds and executes tests.

Note: the CLI is primarily used to test an entire project, not a specific file. For more specific configuration and advanced usage, see Configuration and Programmatic API.

Usage

Let's assume we wrote a index.d.ts type definition for our concat module.

declare const concat: {
	(value1: string, value2: string): string;
	(value1: number, value2: number): string;
};

export default concat;

In order to test this definition, add a index.test-d.ts file.

import concat from '.';

concat('foo', 'bar');
concat(1, 2);

Running npx tsd as a command will verify that the type definition works correctly.

Let's add some extra assertions. We can assert the return type of our function call to match a certain type.

import {expectType} from 'tsd';
import concat from '.';

expectType<string>(concat('foo', 'bar'));
expectType<string>(concat(1, 2));

The tsd command will succeed again.

We change our implementation and type definition to return a number when both inputs are of type number.

declare const concat: {
	(value1: string, value2: string): string;
	(value1: number, value2: number): number;
};

export default concat;

If we don't change the test file and we run the tsd command again, the test will fail.

Strict type assertions

Type assertions are strict. This means that if you expect the type to be string | number but the argument is of type string, the tests will fail.

import {expectType} from 'tsd';
import concat from '.';

expectType<string>(concat('foo', 'bar'));
expectType<string | number>(concat('foo', 'bar'));

If we run tsd, we will notice that it reports an error because the concat method returns the type string and not string | number.

If you still want loose type assertion, you can use expectAssignable for that.

import {expectType, expectAssignable} from 'tsd';
import concat from '.';

expectType<string>(concat('foo', 'bar'));
expectAssignable<string | number>(concat('foo', 'bar'));

Top-level await

If your method returns a Promise, you can use top-level await to resolve the value instead of wrapping it in an async IIFE.

import {expectType, expectError} from 'tsd';
import concat from '.';

expectType<Promise<string>>(concat('foo', 'bar'));

expectType<string>(await concat('foo', 'bar'));

expectError(await concat(true, false));

Order of Operations

When searching for .test-d.ts files and executing them, tsd does the following:

  1. Locates the project's package.json, which needs to be in the current or specified directory (e.g. /path/to/project or process.cwd()). Fails if none is found.

  2. Finds a .d.ts file, checking to see if one was specified manually or in the types field of the package.json. If neither is found, attempts to find one in the project directory named the same as the main field of the package.json or index.d.ts. Fails if no .d.ts file is found.

  3. Finds .test-d.ts and .test-d.tsx files, which can either be in the project's root directory, a specific folder (by default /[project-root]/test-d), or specified individually programatically or via the CLI. Fails if no test files are found.

  4. Runs the .test-d.ts files through the TypeScript compiler and statically analyzes them for errors.

  5. Checks the errors against assertions and reports any mismatches.

Assertions

expectType<T>(expression: T)

Asserts that the type of expression is identical to type T.

expectNotType<T>(expression: any)

Asserts that the type of expression is not identical to type T.

expectAssignable<T>(expression: T)

Asserts that the type of expression is assignable to type T.

expectNotAssignable<T>(expression: any)

Asserts that the type of expression is not assignable to type T.

expectError<T = any>(expression: T)

Asserts that expression throws an error. Will not ignore syntax errors.

expectDeprecated(expression: any)

Asserts that expression is marked as @deprecated.

expectNotDeprecated(expression: any)

Asserts that expression is not marked as @deprecated.

printType(expression: any)

Prints the type of expression as a warning.

Useful if you don't know the exact type of the expression passed to printType() or the type is too complex to write out by hand.

expectNever(expression: never)

Asserts that the type and return type of expression is never.

Useful for checking that all branches are covered.

expectDocCommentIncludes<T>(expression: any)

Asserts that the documentation comment of expression includes string literal type T.

Configuration

tsd is designed to be used with as little configuration as possible. However, if you need a bit more control, a project's package.json and the tsd CLI offer a limited set of configurations.

For more advanced use cases (such as integrating tsd with testing frameworks), see Programmatic API.

Via package.json

tsd uses a project's package.json to find types and test files as well as for some configuration. It must exist in the path given to tsd.

For more information on how tsd finds a package.json, see Order of Operations.

Test Directory

When you have spread your tests over multiple files, you can store all those files in a test directory called test-d. If you want to use another directory name, you can change it in your project's package.json:

{
	"name": "my-module",
	"tsd": {
		"directory": "my-test-dir"
	}
}

Now you can put all your test files in the my-test-dir directory.

Custom TypeScript Config

By default, tsd applies the following configuration:

{
	"strict": true,
	"jsx": "react",
	"target": "es2020",
	"lib": [
		"es2020",
		"dom",
		"dom.iterable"
	],
	"module": "commonjs",
	"esModuleInterop": true,
	"noUnusedLocals": false,
	// The following options are set and are not overridable.
	// Set to `nodenext` if `module` is `nodenext`, `node16` if `module` is `node16` or `node` otherwise.
	"moduleResolution": "node" | "node16" | "nodenext",
	"skipLibCheck": false
}

These options will be overridden if a tsconfig.json file is found in your project. You also have the possibility to provide a custom config by specifying it in package.json:

{
	"name": "my-module",
	"tsd": {
		"compilerOptions": {
			"strict": false
		}
	}
}

Default options will apply if you don't override them explicitly. You can't override the moduleResolution or skipLibCheck options.

Via the CLI

The tsd CLI is designed to test a whole project at once, and as such only offers a couple of flags for configuration.

--typings

Alias: -t

Path to the type definition file you want to test. Same as typingsFile.

--files

Alias: -f

An array of test files with their path. Same as testFiles.

Programmatic API

You can use the programmatic API to retrieve the diagnostics and do something with them. This can be useful to run the tests with AVA, Jest or any other testing framework.

import tsd from 'tsd';

const diagnostics = await tsd();

console.log(diagnostics.length);
//=> 2

You can also make use of the CLI's formatter to generate the same formatting output when running tsd programmatically.

import tsd, {formatter} from 'tsd';

const formattedDiagnostics = formatter(await tsd());

tsd(options?)

Retrieve the type definition diagnostics of the project.

options

Type: object

cwd

Type: string
Default: process.cwd()

Current working directory of the project to retrieve the diagnostics for.

typingsFile

Type: string
Default: The types property in package.json.

Path to the type definition file you want to test. This can be useful when using a test runner to test specific type definitions per test.

testFiles

Type: string[]
Default: Finds files with .test-d.ts or .test-d.tsx extension.

An array of test files with their path. Uses globby under the hood so that you can fine tune test file discovery.

More Repositories

1

listr

Terminal task list
JavaScript
3,194
star
2

alfred-fkill

Alfred 3 workflow to fabulously search and kill processes
JavaScript
473
star
3

dev-time-cli

Get the current local time of a GitHub user.
JavaScript
181
star
4

generator-alfred

Scaffold out an Alfred workflow
JavaScript
169
star
5

babel-engine-plugin

Webpack plugin that transpiles dependencies targeting Node.js versions newer than Node.js 0.10
JavaScript
166
star
6

decode-uri-component

A better decodeURIComponent
JavaScript
144
star
7

clinton

Project style linter
JavaScript
124
star
8

alfred-updater

Alfred workflow updater
JavaScript
107
star
9

mobicon-cli

Mobile icon generator
JavaScript
102
star
10

expiry-map

A Map implementation with expirable items
TypeScript
92
star
11

vscode-yo

Yeoman plugin for VS Code
TypeScript
88
star
12

uppercamelcase

Convert a dash/dot/underscore/space separated string to UpperCamelCase: foo-bar → FooBar
JavaScript
81
star
13

vscode-ava

Snippets for AVA
72
star
14

alfred-notifier

Update notifications for your Alfred workflow
JavaScript
71
star
15

alfred-link

Make your Alfred workflows installable from npm
JavaScript
68
star
16

mobisplash-cli

Mobile app splash screen generator
JavaScript
65
star
17

clean-regexp

Clean up regular expressions
JavaScript
61
star
18

dynongo

MongoDB like syntax for DynamoDB
TypeScript
58
star
19

dev-time

Get the current local time of a GitHub user.
JavaScript
57
star
20

aws-lambda-mock-context

AWS Lambda mock context object
JavaScript
52
star
21

mongoose-seeder

Seed your MongoDB database easily
JavaScript
48
star
22

bragg

AWS λ web framework
JavaScript
47
star
23

ngx-ow

Angular form validation on steroids
TypeScript
45
star
24

mobisplash

Mobile app splash screen generator
JavaScript
45
star
25

alfred-ng

Search through the Angular documentation on angular.io
JavaScript
44
star
26

obsify

Observableify a callback-style function
JavaScript
41
star
27

alfred-config

Allow easy user configurations for your Alfred workflows
JavaScript
41
star
28

gulp-cordova

Documentation of gulp-cordova
40
star
29

ngx-monaco

Monaco Editor for Angular
TypeScript
39
star
30

alfred-font-awesome

Alfred workflow to search for font-awesome icons
JavaScript
37
star
31

listr-update-renderer

Listr update renderer
JavaScript
37
star
32

listr-input

Input module for Listr
JavaScript
33
star
33

aws-lambda-stop-server

AWS Lambda function that will stop servers.
JavaScript
32
star
34

alfred-rxjs

Search through the RxJS documentation
JavaScript
29
star
35

angular2-polyfill

Angular2 polyfill for Angular1
TypeScript
29
star
36

got4aws

Convenience wrapper for Got to interact with AWS v4 signed APIs
TypeScript
27
star
37

observable-conf

Listen for changes in your conf config
JavaScript
27
star
38

aws-lambda-start-server

AWS Lambda function that will start servers.
TypeScript
25
star
39

mobicon

Mobile icon generator
JavaScript
25
star
40

kap-s3

Kap plugin - Share on Amazon S3
JavaScript
25
star
41

tsd-typescript

TypeScript with some extras for type-checking.
JavaScript
22
star
42

vscode-final-newline

Inserts a final newline when saving the document.
TypeScript
22
star
43

aws-lambda-invoke

Invoke AWS Lambda functions with ease
JavaScript
22
star
44

cache-conf

Simple cache config handling for your app or module
JavaScript
21
star
45

alfy-test

Test your Alfy workflows
JavaScript
21
star
46

alfred-aws

Search through the AWS JavaScript SDK
JavaScript
21
star
47

alfred-node

Alfred 3 workflow to search for Node.js documentation
JavaScript
19
star
48

map-age-cleaner

Cleanup expired items in a Map
TypeScript
18
star
49

expiry-set

A Set implementation with expirable keys
TypeScript
16
star
50

stats-map

Map that keeps track of the hits and misses
JavaScript
16
star
51

generator-aws-lambda

Scaffold out an AWS Lambda module.
JavaScript
16
star
52

gulp-cordova-build-android

Gulp plugin for building an android Cordova project
JavaScript
14
star
53

vinyl-read

Create vinyl files from glob patterns
JavaScript
13
star
54

cordova-config

Parse and edit the config.xml file of a cordova project
JavaScript
13
star
55

listr-verbose-renderer

Listr verbose renderer
JavaScript
13
star
56

obj-clean

Remove empty objects, empty strings, null and undefined values from objects.
JavaScript
12
star
57

aws-sns-publish

Publish messages to AWS SNS
JavaScript
12
star
58

vali-date

Validate a date
JavaScript
12
star
59

resolve-alfred-prefs

Resolve the path of Alfred.alfredpreferences
JavaScript
11
star
60

dynamo-seeder

Seed your DynamoDB database easily
JavaScript
11
star
61

angular-ga

Google Analytics for your Angular application
TypeScript
11
star
62

tz-format

Format a date with timezone
JavaScript
10
star
63

ng2-hello-world

Angular2 Hello World starter application
JavaScript
10
star
64

rfpify

[DEPRECATED] Promisify a result-first callback function.
JavaScript
10
star
65

aws-lambda-pify

Promisify an AWS lambda function.
JavaScript
9
star
66

get-gravatar-cli

Get a Gravatar image
JavaScript
9
star
67

kap-plugin-test

Test your Kap plugins
JavaScript
9
star
68

gulp-api-doc

RESTful web API Documentation Generator for Gulp
JavaScript
9
star
69

alfred-css-triggers

Alfred workflow to search through csstriggers.com
JavaScript
8
star
70

listr-silent-renderer

Supress Listr rendering output
JavaScript
8
star
71

ngx-api-gateway-client

AWS API Gateway Client for Angular
TypeScript
8
star
72

travis-got

Convenience wrapper for `got` to interact with the Travis API
JavaScript
7
star
73

github-parse-link

Parse GitHub `link` header response
JavaScript
7
star
74

npm-publish-index-test

JavaScript
6
star
75

kap-plugin-mock-context

Kap plugin mock context
JavaScript
6
star
76

parse-aws-lambda-name

Parse an AWS Lambda function name into a name and a qualifier
JavaScript
6
star
77

beRail

beRail is a BlackBerry 10 application for the belgian railways.
C++
5
star
78

promise-concurrent

Execute a list of promises with a limited concurrency
JavaScript
5
star
79

alfred-ionic

Search through the Ionic documentation
JavaScript
5
star
80

capture-pdf

Capture html in a pdf buffer
JavaScript
5
star
81

BB10-OAuth

OAuth framework for BlackBerry10
C++
5
star
82

latest-push

Get the latest push of a GitHub user.
JavaScript
5
star
83

node-mongoose-validator

Easily validate mongoose schema paths.
JavaScript
5
star
84

gulp-cordova-plugin

This library adds a cordova plugin to the cordova project
JavaScript
4
star
85

string-occurrence

Get the number of occurrences of a string in a string
JavaScript
4
star
86

sam-playground

JavaScript
4
star
87

dynongo-pager

Easy paging for DynamoDB with dynongo
TypeScript
4
star
88

ng2-hello-world-lazy-routing

Angular2 Hello World lazy routing application
JavaScript
4
star
89

gh-lint-brainstorm

Brainstorming repository for a repository linter
4
star
90

regex-occurrence

Get the number of occurrences of a RegExp in a string
JavaScript
4
star
91

is-d

Check if a file is a directory
JavaScript
3
star
92

Take-A-Look-Inside-Web

Web version for take a look inside
JavaScript
3
star
93

gulp-cordova-build-ios

Gulp plugin for building an iOS Cordova project
JavaScript
3
star
94

dynamo-discovery-service

Discovery service like etcd but implemented with DynamoDB
JavaScript
3
star
95

lambda-update-alias

Update or create a AWS lambda alias
JavaScript
2
star
96

dynamo-discovery-service-cli

CLI for the discovery service
JavaScript
2
star
97

amplify-starter

JavaScript
2
star
98

get-exec-file

Promisify execFile
JavaScript
2
star
99

angular2-polyfill-heroes

Tour of Heroes implementation with angular2-polyfill
TypeScript
2
star
100

bragg-sns

SNS middleware for bragg
JavaScript
2
star