### Install tsd CLI Source: https://github.com/tsdjs/tsd/blob/main/readme.md Installs the tsd package as a development dependency using npm. ```sh npm install --save-dev tsd ``` -------------------------------- ### Integrate tsd with AVA for type checking Source: https://context7.com/tsdjs/tsd/llms.txt Integrate tsd into AVA test suites to verify TypeScript type definitions. This example shows how to run tsd to check all type definitions or specific files and assert the absence of diagnostic errors. ```typescript import test from 'ava'; import tsd from 'tsd'; test('type definitions are correct', async t => { const diagnostics = await tsd({ cwd: __dirname }); t.is(diagnostics.length, 0, 'No type errors expected'); }); test('specific type file has no errors', async t => { const diagnostics = await tsd({ cwd: __dirname, typingsFile: './lib/api.d.ts', testFiles: ['./test/api.test-d.ts'] }); t.deepEqual(diagnostics, []); }); ``` -------------------------------- ### Programmatic API with Formatter for tsd Diagnostics Source: https://github.com/tsdjs/tsd/blob/main/readme.md Shows how to use the tsd programmatic API along with the formatter to get diagnostics in a formatted string. This is useful for consistent output across different testing environments. ```typescript import tsd, {formatter} from 'tsd'; const formattedDiagnostics = formatter(await tsd()); ``` -------------------------------- ### Integrate tsd with Jest for type checking Source: https://context7.com/tsdjs/tsd/llms.txt Integrate tsd into Jest test suites to ensure type definitions are correct. This example demonstrates running tsd and asserting that no diagnostic errors are found, failing the test if errors exist. ```typescript import tsd, { formatter } from 'tsd'; describe('Type Definitions', () => { it('should have no type errors', async () => { const diagnostics = await tsd({ cwd: process.cwd() }); if (diagnostics.length > 0) { fail(formatter(diagnostics, true)); } expect(diagnostics).toHaveLength(0); }); }); ``` -------------------------------- ### Assertion: expectType Source: https://context7.com/tsdjs/tsd/llms.txt Asserts that the type of an expression is strictly identical to a specified type T. This is a precise check; for example, `string` is not identical to `string | number`. It's useful for ensuring exact type matches. ```typescript import { expectType } from 'tsd'; import myFunction from './my-module'; // These pass - exact type match expectType(myFunction('hello')); expectType(myFunction(42)); expectType>(myFunction.async('hello')); // This fails - number is not identical to string expectType(myFunction(42)); // Error! // This fails - string is not identical to string | number expectType(myFunction('hello')); // Error! // Works with complex types expectType(new Date('2024-01-01')); expectType>(Promise.resolve(42)); ``` -------------------------------- ### Run tsd CLI Tests Source: https://context7.com/tsdjs/tsd/llms.txt Execute tsd tests from the command line. This command searches for .d.ts files and their corresponding .test-d.ts test files within the project directory. Options allow specifying custom typings files or test file patterns. ```bash npx tsd npx tsd /path/to/project npx tsd --typings ./custom-types.d.ts npx tsd --files ./test/**/*.test-d.ts --files ./other-tests/*.test-d.tsx npx tsd --show-diff ``` -------------------------------- ### Run tsd CLI for Project Testing Source: https://github.com/tsdjs/tsd/blob/main/readme.md Executes the tsd CLI to test type definitions in the current or specified directory. The CLI searches for .d.ts files and corresponding .test-d.ts files for analysis. ```sh npx tsd [path] ``` -------------------------------- ### Basic tsd Test File Source: https://github.com/tsdjs/tsd/blob/main/readme.md A sample .test-d.ts file to test the 'concat' type definition. It imports the function and calls it with valid arguments. ```ts import concat from '.'; concat('foo', 'bar'); concat(1, 2); ``` -------------------------------- ### Top-level Await Support Source: https://context7.com/tsdjs/tsd/llms.txt Demonstrates tsd's support for top-level `await`, allowing direct testing of Promise-returning functions without needing to wrap them in an async IIFE. ```APIDOC ## Top-level Await Support ### Description tsd supports top-level `await` for testing Promise-returning functions without wrapping in async IIFE. ### Usage Top-level await can be used directly in your test files to test promises and their resolved values. ### Example ```typescript import { expectType, expectError } from 'tsd'; import asyncConcat from './async-concat'; // Test the Promise type directly expectType>(asyncConcat('foo', 'bar')); // Test the resolved value using top-level await expectType(await asyncConcat('foo', 'bar')); expectType(await asyncConcat(1, 2)); // Expect error with await expectError(await asyncConcat(true, false)); ``` ### Response This feature enables more concise testing of asynchronous operations by allowing `await` at the top level of test modules. ``` -------------------------------- ### tsd Test File with Top-Level Await and expectError Source: https://github.com/tsdjs/tsd/blob/main/readme.md Shows how to use top-level await with Promises and 'expectError' to assert expected type errors in a .test-d.ts file. ```ts import {expectType, expectError} from 'tsd'; import concat from '.'; expectType>(concat('foo', 'bar')); expectType(await concat('foo', 'bar')); expectError(await concat(true, false)); ``` -------------------------------- ### tsd Test File with Strict and Loose Type Assertions Source: https://github.com/tsdjs/tsd/blob/main/readme.md Demonstrates using both 'expectType' for strict type checking and 'expectAssignable' for looser type checking in a .test-d.ts file. ```ts import {expectType, expectAssignable} from 'tsd'; import concat from '.'; expectType(concat('foo', 'bar')); expectAssignable(concat('foo', 'bar')); ``` -------------------------------- ### JSON Configuration for tsd Directory Source: https://github.com/tsdjs/tsd/blob/main/readme.md Specifies a custom directory for test files in the package.json file. This allows organizing test files outside the default 'test-d' directory. ```json { "name": "my-module", "tsd": { "directory": "my-test-dir" } } ``` -------------------------------- ### Configure tsd via package.json Source: https://context7.com/tsdjs/tsd/llms.txt Configure tsd's behavior by adding a 'tsd' property to your project's package.json file. This allows customization of the test directory and TypeScript compiler options specific to type checking. ```json { "name": "my-module", "types": "./dist/index.d.ts", "tsd": { "directory": "my-test-dir", "compilerOptions": { "strict": false, "esModuleInterop": true, "lib": ["es2020", "dom"], "target": "es2020", "module": "commonjs" } } } ``` -------------------------------- ### JSON Configuration for Custom TypeScript Compiler Options Source: https://github.com/tsdjs/tsd/blob/main/readme.md Allows overriding default TypeScript compiler options for tsd tests by specifying them in package.json. Note that 'moduleResolution' and 'skipLibCheck' cannot be overridden. ```json { "name": "my-module", "tsd": { "compilerOptions": { "strict": false } } } ``` -------------------------------- ### Programmatic API: tsd Function Source: https://context7.com/tsdjs/tsd/llms.txt The main tsd function retrieves type definition diagnostics for a project. It returns a promise resolving to an array of diagnostics. Options can configure the working directory, typings file, and test files using glob patterns. ```typescript import tsd from 'tsd'; // Basic usage with default options const diagnostics = await tsd(); console.log(`Found ${diagnostics.length} type errors`); // With custom working directory const diagnostics = await tsd({ cwd: '/path/to/your/project' }); // With custom typings file const diagnostics = await tsd({ cwd: process.cwd(), typingsFile: './lib/custom-types.d.ts' }); // With custom test files (supports glob patterns) const diagnostics = await tsd({ cwd: process.cwd(), testFiles: ['./test/**/*.test-d.ts', './src/**/*.test-d.tsx'] }); // Process diagnostics for (const diagnostic of diagnostics) { console.log(`${diagnostic.fileName}:${diagnostic.line}:${diagnostic.column}`); console.log(` ${diagnostic.severity}: ${diagnostic.message}`); } ``` -------------------------------- ### Programmatic API Usage for tsd Diagnostics Source: https://github.com/tsdjs/tsd/blob/main/readme.md Demonstrates how to use the tsd programmatic API to retrieve type definition diagnostics. The 'tsd()' function returns a promise that resolves with an array of diagnostics. ```typescript import tsd from 'tsd'; const diagnostics = await tsd(); console.log(diagnostics.length); //=> 2 ``` -------------------------------- ### Top-Level Await Support in tsd Source: https://context7.com/tsdjs/tsd/llms.txt tsd supports top-level `await` for testing Promise-returning functions directly, eliminating the need for async IIFEs. This simplifies testing asynchronous operations. ```typescript import { expectType, expectError } from 'tsd'; import asyncConcat from './async-concat'; // Test the Promise type directly expectType>(asyncConcat('foo', 'bar')); // Test the resolved value using top-level await expectType(await asyncConcat('foo', 'bar')); expectType(await asyncConcat(1, 2)); // Expect error with await expectError(await asyncConcat(true, false)); ``` -------------------------------- ### Programmatic API: formatter Function Source: https://context7.com/tsdjs/tsd/llms.txt The formatter function takes an array of TypeScript diagnostics and an optional boolean to show diffs, returning a human-readable string output. It's useful for displaying test results in a user-friendly format, similar to eslint-formatter-pretty. ```typescript import tsd, { formatter } from 'tsd'; const diagnostics = await tsd({ cwd: '/path/to/project' }); // Basic formatting const output = formatter(diagnostics); console.log(output); // With type diff display for easier debugging const outputWithDiff = formatter(diagnostics, true); console.log(outputWithDiff); // Example output: // index.test-d.ts // ✖ 10:20 Argument of type string is not assignable to parameter of type number. ``` -------------------------------- ### Basic TypeScript Type Definition Source: https://github.com/tsdjs/tsd/blob/main/readme.md A sample TypeScript declaration file (index.d.ts) defining an overloaded 'concat' function. ```ts declare const concat: { (value1: string, value2: string): string; (value1: number, value2: number): string; }; export default concat; ``` -------------------------------- ### expectError Source: https://context7.com/tsdjs/tsd/llms.txt Asserts that a given expression produces a TypeScript error. It does not ignore syntax errors and is useful for verifying that incorrect usage leads to type errors. ```APIDOC ## expectError(expression) ### Description Asserts that the expression produces a TypeScript error. Will **not** ignore syntax errors. ### Method `expectError` ### Parameters #### Arguments - **expression**: The expression expected to produce a TypeScript error. ### Request Example ```typescript import { expectError } from 'tsd'; import concat, { add, processArray } from './my-module'; // Expect error when passing wrong argument types expectError(concat(true, true)); // boolean not allowed expectError(concat('foo', 'bar')); // if overload doesn't accept strings // Expect error for wrong number of arguments expectError(add(1)); // missing second argument expectError(add(1, 2, 3)); // too many arguments // Works with multiple type errors in single assertion expectError(processArray(['a', 'bad'])); // invalid array structure ``` ### Response This function does not return a value but throws an error if the expression does not produce a TypeScript error. ``` -------------------------------- ### tsd Test File with expectType Assertions Source: https://github.com/tsdjs/tsd/blob/main/readme.md A .test-d.ts file using 'expectType' from 'tsd' to assert the return types of the 'concat' function calls. ```ts import {expectType} from 'tsd'; import concat from '.'; expectType(concat('foo', 'bar')); expectType(concat(1, 2)); ``` -------------------------------- ### expectDeprecated Source: https://context7.com/tsdjs/tsd/llms.txt Asserts that a given expression (function, class, property, enum member) is marked with the `@deprecated` JSDoc tag. ```APIDOC ## expectDeprecated(expression) ### Description Asserts that the expression is marked with the `@deprecated` JSDoc tag. ### Method `expectDeprecated` ### Parameters #### Arguments - **expression**: The expression (e.g., function, class, property) to check for the `@deprecated` tag. ### Request Example ```typescript import { expectDeprecated } from 'tsd'; import { oldFunction, OldClass, Options } from './my-module'; // Function marked as @deprecated expectDeprecated(oldFunction); // Class marked as @deprecated expectDeprecated(OldClass); // Property marked as @deprecated declare const options: Options; expectDeprecated(options.legacyMode); // Enum member marked as @deprecated expectDeprecated(MyEnum.OLD_VALUE); ``` ### Response This function does not return a value but throws an error if the expression is not marked as deprecated. ``` -------------------------------- ### expectDocCommentIncludes Source: https://context7.com/tsdjs/tsd/llms.txt Asserts that the documentation comment (JSDoc) of an expression includes a specific string literal type `T`. Useful for verifying documentation accuracy. ```APIDOC ## expectDocCommentIncludes(expression) ### Description Asserts that the documentation comment (JSDoc) of the expression includes the string literal type `T`. ### Method `expectDocCommentIncludes` ### Parameters #### Type Parameters - **T**: The string literal type that is expected to be included in the documentation comment. #### Arguments - **expression**: The expression (e.g., variable, function) whose documentation comment is to be checked. ### Request Example ```typescript import { expectDocCommentIncludes } from 'tsd'; /** FooBar - This is a documented constant */ declare const foo: string; // Pass - doc comment includes these strings expectDocCommentIncludes<'FooBar'>(foo); expectDocCommentIncludes<'Foo'>(foo); expectDocCommentIncludes<'Bar'>(foo); // Fail - doc comment doesn't include 'Baz' expectDocCommentIncludes<'Baz'>(foo); // Error! // Fail - no doc comment on expression const undocumented = 'value'; expectDocCommentIncludes<'anything'>(undocumented); // Error! ``` ### Response This function does not return a value but throws an error if the documentation comment does not include the specified string literal type or if the expression is undocumented. ``` -------------------------------- ### expectNotDeprecated Source: https://context7.com/tsdjs/tsd/llms.txt Asserts that a given expression is **not** marked with the `@deprecated` JSDoc tag. Useful for ensuring that new or updated code does not carry deprecation warnings. ```APIDOC ## expectNotDeprecated(expression) ### Description Asserts that the expression is **not** marked with the `@deprecated` JSDoc tag. ### Method `expectNotDeprecated` ### Parameters #### Arguments - **expression**: The expression (e.g., function, class, property) to check for the absence of the `@deprecated` tag. ### Request Example ```typescript import { expectNotDeprecated } from 'tsd'; import { newFunction, NewClass, Options } from './my-module'; // Function not marked as @deprecated expectNotDeprecated(newFunction); // Class not marked as @deprecated expectNotDeprecated(NewClass); // Property not marked as @deprecated declare const options: Options; expectNotDeprecated(options.enabled); ``` ### Response This function does not return a value but throws an error if the expression is marked as deprecated. ``` -------------------------------- ### printType Source: https://context7.com/tsdjs/tsd/llms.txt Prints the type of a given expression as a warning during the test run. This is a debugging tool to help understand complex types. ```APIDOC ## printType(expression) ### Description Prints the type of the expression as a warning. Useful for debugging complex types. ### Method `printType` ### Parameters #### Arguments - **expression**: The expression whose type should be printed. ### Request Example ```typescript import { printType } from 'tsd'; declare const complexValue: { nested: { deeply: { value: string } }; array: number[]; }; // Prints type as warning during test run printType(complexValue); // Warning: { nested: { deeply: { value: string } }; array: number[] } printType(null); // Warning: null printType(undefined); // Warning: undefined printType('foo'); // Warning: "foo" printType(null as any); // Warning: any ``` ### Response This function does not return a value. It outputs the type of the expression as a warning. ``` -------------------------------- ### Assertion: expectAssignable Source: https://context7.com/tsdjs/tsd/llms.txt Asserts that the type of an expression is assignable to a specified type T. This is a more lenient check than `expectType`, allowing for broader type compatibility. ```typescript import { expectAssignable } from 'tsd'; import concat from './concat'; // Pass - string is assignable to string | number expectAssignable(concat('foo', 'bar')); // Pass - number is assignable to string | number expectAssignable(concat(1, 2)); // Pass - any type is assignable to any expectAssignable(concat(1, 2)); // Fail - string is not assignable to boolean expectAssignable(concat('unicorn', 'rainbow')); // Error! ``` -------------------------------- ### expectNever Source: https://context7.com/tsdjs/tsd/llms.txt Asserts that the type of an expression is `never`. This is particularly useful for verifying exhaustive pattern matching in switch statements or other control flow structures. ```APIDOC ## expectNever(expression) ### Description Asserts that the type of the expression is `never`. Useful for checking exhaustive pattern matching. ### Method `expectNever` ### Parameters #### Arguments - **expression**: The expression whose type is expected to be `never`. ### Request Example ```typescript import { expectNever } from 'tsd'; type Status = 'pending' | 'success' | 'error'; function handleStatus(status: Status): string { switch (status) { case 'pending': return 'Loading...'; case 'success': return 'Done!'; case 'error': return 'Failed!'; default: // If all cases are handled, status is `never` here expectNever(status); return status; } } // Also works with functions that return never declare function throwError(): never; expectNever(throwError()); ``` ### Response This function does not return a value but throws an error if the expression's type is not `never`. ``` -------------------------------- ### expectNotAssignable Source: https://context7.com/tsdjs/tsd/llms.txt Asserts that the type of an expression is not assignable to a specified type `T`. This is useful for ensuring type mismatches are correctly caught. ```APIDOC ## expectNotAssignable(expression) ### Description Asserts that the type of the expression is **not assignable** to type `T`. ### Method `expectNotAssignable` ### Parameters #### Type Parameters - **T**: The target type to check assignability against. #### Arguments - **expression**: The expression whose type is to be checked. ### Request Example ```typescript import { expectNotAssignable } from 'tsd'; const str: string = 'hello'; const num: number = 42; // Pass - string is not assignable to number expectNotAssignable(str); // Pass - number is not assignable to string expectNotAssignable(num); // Fail - string is assignable to string | number expectNotAssignable(str); // Error! ``` ### Response This function does not return a value but throws an error if the type assignability check fails. ``` -------------------------------- ### Print Type Information with tsd Source: https://context7.com/tsdjs/tsd/llms.txt The `printType` function prints the type of an expression as a warning during test execution. This is a valuable debugging tool for understanding complex types. ```typescript import { printType } from 'tsd'; declare const complexValue: { nested: { deeply: { value: string } }; array: number[]; }; // Prints type as warning during test run printType(complexValue); // Warning: { nested: { deeply: { value: string } }; array: number[] } printType(null); // Warning: null printType(undefined); // Warning: undefined printType('foo'); // Warning: "foo" printType(null as any); // Warning: any ``` -------------------------------- ### TypeScript Type Definition with Number Return Type Source: https://github.com/tsdjs/tsd/blob/main/readme.md An updated TypeScript declaration file where the 'concat' function returns a number when both inputs are numbers. ```ts declare const concat: { (value1: string, value2: string): string; (value1: number, value2: number): number; }; export default concat; ``` -------------------------------- ### Assert Doc Comment Includes String with tsd Source: https://context7.com/tsdjs/tsd/llms.txt Use `expectDocCommentIncludes` to assert that the documentation comment (JSDoc) of an expression includes a specific string literal type `T`. This verifies that documentation is present and accurate. ```typescript import { expectDocCommentIncludes } from 'tsd'; /** FooBar - This is a documented constant */ declare const foo: string; // Pass - doc comment includes these strings expectDocCommentIncludes<'FooBar'>(foo); expectDocCommentIncludes<'Foo'>(foo); expectDocCommentIncludes<'Bar'>(foo); // Fail - doc comment doesn't include 'Baz' expectDocCommentIncludes<'Baz'>(foo); // Error! // Fail - no doc comment on expression const undocumented = 'value'; expectDocCommentIncludes<'anything'>(undocumented); // Error! ``` -------------------------------- ### Assert Deprecated Status with tsd Source: https://context7.com/tsdjs/tsd/llms.txt Use `expectDeprecated` to assert that an expression (function, class, property, or enum member) is marked with the `@deprecated` JSDoc tag. This helps ensure that deprecated features are correctly identified. ```typescript import { expectDeprecated } from 'tsd'; import { oldFunction, OldClass, Options } from './my-module'; // Function marked as @deprecated expectDeprecated(oldFunction); // Class marked as @deprecated expectDeprecated(OldClass); // Property marked as @deprecated declare const options: Options; expectDeprecated(options.legacyMode); // Enum member marked as @deprecated expectDeprecated(MyEnum.OLD_VALUE); ``` -------------------------------- ### Assertion: expectNotType Source: https://context7.com/tsdjs/tsd/llms.txt Asserts that the type of an expression is not identical to a specified type T. This is the inverse of `expectType` and is used to verify that a type is different from a given type. ```typescript import { expectNotType } from 'tsd'; import concat from './concat'; // Pass - string is not identical to number expectNotType(concat('foo', 'bar')); // Pass - string is not identical to string | number expectNotType(concat('foo', 'bar')); // Fail - string is identical to string expectNotType(concat('unicorn', 'rainbow')); // Error! ``` -------------------------------- ### Assert Not Deprecated Status with tsd Source: https://context7.com/tsdjs/tsd/llms.txt The `expectNotDeprecated` function asserts that an expression is **not** marked with the `@deprecated` JSDoc tag. This is useful for verifying that newer or updated code does not carry deprecation warnings. ```typescript import { expectNotDeprecated } from 'tsd'; import { newFunction, NewClass, Options } from './my-module'; // Function not marked as @deprecated expectNotDeprecated(newFunction); // Class not marked as @deprecated expectNotDeprecated(NewClass); // Property not marked as @deprecated declare const options: Options; expectNotDeprecated(options.enabled); ``` -------------------------------- ### Assert TypeScript Error with tsd Source: https://context7.com/tsdjs/tsd/llms.txt The `expectError` function asserts that a given expression produces a TypeScript error. It does not ignore syntax errors and is useful for testing incorrect type usage or argument mismatches. ```typescript import { expectError } from 'tsd'; import concat, { add, processArray } from './my-module'; // Expect error when passing wrong argument types expectError(concat(true, true)); // boolean not allowed expectError(concat('foo', 'bar')); // if overload doesn't accept strings // Expect error for wrong number of arguments expectError(add(1)); // missing second argument expectError(add(1, 2, 3)); // too many arguments // Works with multiple type errors in single assertion expectError(processArray(['a', 'bad'])); // invalid array structure ``` -------------------------------- ### Assert Type is Never with tsd Source: https://context7.com/tsdjs/tsd/llms.txt Use `expectNever` to assert that the type of an expression is `never`. This is particularly useful for ensuring exhaustive pattern matching in switch statements or type guards. ```typescript import { expectNever } from 'tsd'; type Status = 'pending' | 'success' | 'error'; function handleStatus(status: Status): string { switch (status) { case 'pending': return 'Loading...'; case 'success': return 'Done!'; case 'error': return 'Failed!'; default: // If all cases are handled, status is `never` here expectNever(status); return status; } } // Also works with functions that return never declare function throwError(): never; expectNever(throwError()); ``` -------------------------------- ### Assert Type Not Assignable with tsd Source: https://context7.com/tsdjs/tsd/llms.txt Use `expectNotAssignable` to assert that the type of an expression is not assignable to a specified type `T`. This is useful for verifying type constraints and preventing unintended assignments. ```typescript import { expectNotAssignable } from 'tsd'; const str: string = 'hello'; const num: number = 42; // Pass - string is not assignable to number expectNotAssignable(str); // Pass - number is not assignable to string expectNotAssignable(num); // Fail - string is assignable to string | number expectNotAssignable(str); // Error! ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.