Giter VIP home page Giter VIP logo

tsd-lite's Introduction

Caution

tsd-lite is deprecated. It is recommended to migrate to TSTyche.

For details, see the deprecation notice.


tsd-lite

Test your TypeScript types easily.

version license node-ci

This is a lighter version of tsd. Slightly reworked codebase allows tsd-lite to be a tool which simply tests your types.

Motivation

While tsd suites perfectly for JavaScript libraries which declare their types in .d.ts files, its usage with monorepos written in TypeScript may become cumbersome. tsd-lite is an attempt to address these and similar issues.

Differences from tsd

  • tsd-lite performs only type testing without any additional checks or rules.
  • Exposes only general type related assertions: expectAssignable, expectNotAssignable, expectError, expectType and expectNotType. All other APIs (like expectNever, expectDeprecated, expectDocCommentIncludes and printType) are not implement.
  • Comes with no default compiler options.
  • Reads TypeScript compiler options from the nearest tsconfig.json for each test file (does not read options from package.json).
  • tsd-lite is optionally strict. You should add "strict": true to the nearest tsconfig.json (it can be project or test specific) to use strict assertions.
  • @tsd/typescript package is moved to peer dependencies.
  • tsd-lite allows only programmatic usage. For an integration with Jest see jest-runner-tsd, if you prefer standalone CLI implementation check tsd-lite-cli.

Install

yarn add -D tsd-lite @tsd/typescript
# or
npm install -D tsd-lite @tsd/typescript

Remember to install @tsd/typescript. It is a required peer dependency.

Assertions

The library provides the following type testing assertions.

expectAssignable<T>(expression)

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

expectNotAssignable<T>(expression)

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

// JsonObject.ts
type JsonValue = string | number | boolean | JsonObject | Array<JsonValue>;

export interface JsonObject {
  [key: string]: JsonValue;
}
// __typetests__/JsonObject.test.ts
import { expectAssignable, expectNotAssignable } from "tsd-lite";
import type { JsonObject } from "../JsonObject.js";

expectAssignable<JsonObject>({
  caption: "test",
  count: 100,
  isTest: true,
  location: { name: "test", start: [1, 2], valid: false, x: 10, y: 20 },
  values: [0, 10, 20, { x: 1, y: 2 }, true, "test", ["a", "b"]],
});

expectNotAssignable<JsonObject>({
  filter: () => {},
});

expectType<T>(expression)

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

expectNotType<T>(expression)

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

// MethodLikeKeys.ts
type FunctionLike = (...args: any) => any;

export type MethodLikeKeys<T> = keyof {
  [K in keyof T as Required<T>[K] extends FunctionLike ? K : never]: T[K];
};
// __typetests__/MethodLikeKeys.test.ts
import { expectType, expectNotType } from "tsd-lite";
import type { MethodLikeKeys } from "../MethodLikeKeys.js";

interface FixtureInterface {
  methodA?: ((a: boolean) => void) | undefined;
  methodB: (b: string) => boolean;

  propertyA?: number | undefined;
  propertyB?: number;
  propertyC: number | undefined;
  propertyD: string;
}

declare const interfaceMethods: MethodLikeKeys<FixtureInterface>;

expectType<"methodA" | "methodB">(interfaceMethods);
expectNotType<"methodA" | "methodB" | "propertyA">(interfaceMethods);

expectError(expression)

Asserts the expression has a type error.

// __typetests__/require-resolve.test.ts
import { expectError, expectType } from "tsd-lite";

// Expected 1-2 arguments
expectError(require.resolve());

// Returns a value of type 'string'
expectType<string>(require.resolve("tsd-lite"));

API Reference

The default export of the library is a function which takes fully resolved path to a test file as an argument:

import tsdLite from "tsd-lite";

const { assertionsCount, tsdResults } = tsdLite(
  "/absolute/path/to/testFile.test.ts",
);

It returns an object with assertionsCount and tsdResults properties:

{
  assertionsCount: number;
  tsdResults: Array<{
    messageText: string | ts.DiagnosticMessageChain;
    file?: ts.SourceFile;
    start?: number;
  }>;
}

tsd-lite will throw if the TypeScript compiler encounters an error while parsing tsconfig.json or finds a syntax error in the code.

License

MIT

tsd-lite's People

Contributors

andreidmt avatar depfu[bot] avatar hasezoey avatar lokshunhung avatar mrazauskas avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

jolg42 andreidmt

tsd-lite's Issues

`tsd-lite` should work alongside `@ts-ignore` and `@ts-expect-error` comments

Hello! I'm a new user of this package via jest-runner-tsd. Enjoying it so far.

I ran into an issue today while implementing tsd-lite for the first time.

import {expectError} from 'tsd-lite'

type TSomeType = {foo: string}
declare const someObject: TSomeType

expectError(someObject.someMissingKey)

If I write the above code, things work great from tsd's perspective - the expectError line sees a type error, as expected.

However, my IDE (WebStorm) sees the error, too, and complains about it, which makes sense.

TS2339: Property 'someMissingKey' does not exist on type 'TSomeType'.

image

I'd like to avoid having these errors in my editor, which distract me from "real" errors in my project by cluttering my "project errors" console. So, I tried to use //@ts-ignore or the newer //@ts-expect-error feature:

With either flag, my editor is happy, but tsd-lite produces this error when I run the tests:

Expected an error, but found none.

Which kinda makes sense - I am suppressing the error, so I guess tsd-lite can't see it anymore? It'd be nice if this wasn't the case, but I'd understand if this is just a limitation of how the library works. I'm making this issue in hopes that there is a workaround possible here, or to at least document this for other users if not.

Note: I could make this issue over at tsd instead of here, if you think this is more of an upstream issue, but since I'm not using tsd directly, I started here.


I am configuring tsd-lite for the first time, so I wonder if this is partially related to my setup, so I'll quickly describe it here.

Basically I'm wondering if other users of this lib avoid including their test files in a tsconfig, which doesn't work well with my setup.

I've got multiple tsconfig files, one for my regular code and one for my tests. WebStorm doesn't to understand the file imports in my test files unless I have a tsconfig configuration that includes them, which is probably because of other settings I have in my tsconfig, like the paths setting to make an alias for relative imports with a ~. For example:

import {expectError} from 'tsd-lite'
import {ATypeOfMine} from '~/api/types' // '~' is resolved to `./src` via the `.tsconfig` `paths` key

I am not sure if my setup is part of the problem; I'm happy to take any advice on configuration if this problem doesn't occur for other folks.

Global types are breaking type tets

Hi, first of all I wanted to say thank you for the hard work on the library! ๐Ÿ˜ƒ

At our project we wanted to introduce type testing using tsd-lite along with tsd-runner-jest. We did a basic setup according to the docs to make a sort of MVP. The setup is mirrored in this repro repo.

The problem that we encountered is that types from the global scope seem to break the type tests. In this repro we're creating a type test but also importing a function to test its signature. This function is using a global type.

After running npx jest --config jest.config.tsd.js you can see that type ThisIsNull cannot be found, but it is used in the id function. The test would also break if we used ThisIsNull directly in the type tests since it would not
be recognized unless it's explicitly imported (which would make it non-global).

Steps to reproduce:

  1. Clone the repo and install dependencies - git clone followed by npm i
  2. Run the tests - npx jest --config jest.config.tsd.js
  3. Check the result

Actual result:

Expected result:
ThisIsNull type should be known to the runner when importing the id function, error shouldn't be thrown

The question

So we wanted to ask whether we can do something about it right now, maybe we missed something? And if we can - would it require us to get rid of global types or do some hacks to get around problems surrounding them? Or maybe that problem is unsolvable for the time being?

Please let us know, thanks for any help in advance!

CC @erheron

option to specify tsconfig

currently tsd-lite looking only for tsconfig.json, it would be nice to have option to specify tsconfig file name

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): lock file maintenance

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/node-ci.yml
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/setup-node v4@8f152de45cc393bb48ce5d89d36b731f54556e65
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/setup-node v4@8f152de45cc393bb48ce5d89d36b731f54556e65
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/setup-node v4@8f152de45cc393bb48ce5d89d36b731f54556e65
  • actions/checkout v4@b4ffde65f46336ab88eb53be808477a3936bae11
  • actions/setup-node v4@8f152de45cc393bb48ce5d89d36b731f54556e65
npm
package.json
  • @babel/core 7.23.3
  • @babel/preset-env 7.23.3
  • @babel/preset-typescript 7.23.3
  • @jest/globals 29.7.0
  • @tsconfig/node16 16.1.1
  • @tsd/typescript 5.2.2
  • @types/node 20.9.0
  • @typescript-eslint/eslint-plugin 6.11.0
  • @typescript-eslint/parser 6.11.0
  • babel-jest 29.7.0
  • cspell 8.0.0
  • eslint 8.53.0
  • eslint-config-prettier 9.0.0
  • jest 29.7.0
  • prettier 3.1.0
  • typescript 5.2.2
  • @tsd/typescript 4.x || 5.x
  • node >=16
  • yarn 3.6.4

  • Check this box to trigger a request for Renovate to run again on this repository

Deprecation notice

tsd-lite is deprecated.

Support for TypeScript 6 or any new features will not be added.

Meet TSTyche

I recommend migrating to TSTyche โ€“ The Essential Type Testing Tool.

It is a freshly published type testing tool. I developed it recently. A simple idea (jest-community/jest-runner-tsd#32) turned into two years of researching and tinkering. TSTyche has a lot to offer, here are just few highlights:

  • testing on specific versions of Typescript: tstyche --target 5.0,latest;
  • helpers like test() and describe() with .only, .skip run mode flags;
  • expect style assertions to compare two types, or two expressions, or a type with an expression, or an expression with a type;
  • .toRaiseError() matcher to capture exact error message.

Visit https://tstyche.org to view the full documentation.

Migration

As a reference, here are the few migration / usage PRs:

Jest

RedwoodJS

Typegoose

better-enums

.d.ts declaration testing in a JavaScript package:

docusaurus-remark-plugin-tab-blocks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.