First Steps
Learn by example how to use TSTyche.
Prerequisites
The minimum supported Node.js version is 20.9
. It is recommended to use the latest LTS release .
TSTyche supports and tests only against the Long Term Support (LTS) releases of Node.js. Other releases might work too, but keep in mind that only the LTS releases are considered ready for general use.
Install TSTyche
Use your favorite package manager to add tstyche
(and optionally typescript
) to a project:
npm
npm add -D tstyche typescript
It is recommended to create a tsconfig.json
file as well. Run tsc --init
and TypeScript will generate it.
The following steps assume that you installed the typescript
package and added the tsconfig.json
file. TSTyche works just fine without a TSConfig file and TypeScript installed.
Define a Type
Create a MethodLikeKeys.ts
file with the following content:
type = (...: any) => any;
export type <> = keyof {
[ in keyof as [] extends ? : never]: [];
};
The MethodLikeKeys
utility should construct a union type by picking up names of method like keys of the T
type.
Add a Type Test
Create a MethodLikeKeys.tst.ts
file in the same directory:
import { } from "tstyche";
import type { } from "./MethodLikeKeys.js";
interface Sample {
: string;
: () => number;
?: () => number;
}
<<Sample>>()..<"getLength" | "getWidth">();
Here the expect()
function defines an easy to read assertion. There are two method like keys in the Sample
interface, hence the resulting type must be "getLength" | "getWidth"
.
By convention, it is recommended to suffix the unit tests with .test.*
and the type tests with .tst.*
. To learn more, see the File Structure page.
Run the Type Test
All is set. Tell TSTyche to run the type test:
npm
npx tstyche
You should see similar report:
uses TypeScript 5.8.3 with ./tsconfig.json
fail ./MethodLikeKeys.tst.ts
Error: Type '"getLength"' is not the same as type '"getLength" | "getWidth"'.
8 | }
9 |
10 | expect<MethodLikeKeys<Sample>>().type.toBe<"getLength" | "getWidth">();
| ~~~~~~~~~~~~~~~~~~~~~~~~
11 |
at ./MethodLikeKeys.tst.ts:10:44
On the first line you see the TypeScript version used for this test run. It is followed by a path to the TSConfig file from which the compiler configuration was loaded.
The rest reports that the test has failed and explains the problem.
Iterate
The getWidth
key is marked as optional and was not picked up by the MethodLikeKeys
type. Here is the fixed type:
export type <> = keyof {
[ in keyof as <>[] extends ? : never]: [];
};
Run the test again and it will pass:
uses TypeScript 5.8.3 with ./tsconfig.json
pass ./MethodLikeKeys.tst.ts