eslint-plugin-expect-type
ESLint plugin with $ExpectType and $ExpectError type assertions
Installation
Make sure you have TypeScript and @typescript-eslint/parser installed, then install the plugin:
npm i -D eslint-plugin-expect-type
Please also make sure the following packages are also installed:
npm i -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser
Usage
Please add the following options to your .eslintrc
{
"extends": ["plugin:eslint-plugin-expect-type/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"plugins": ["eslint-plugin-expect-type"],
"root": true
}
Rule severity could be configured as follows
{
"rules": {
"expect-type/expect": "error"
}
}
To skip Snapshot update when eslint is run with --fix
could be configured as follows:
{
"rules": {
"expect-type/expect": ["error", { "disableExpectTypeSnapshotFix": true }]
}
}
Note: Make sure to use eslint --ext .js,.ts
since by default eslint
will only search for .js files.
Adding $ExpectType and $ExpectError type assertions
A test file should be a piece of sample code that tests using the library. Tests are type-checked, but not run. To assert that an expression is of a given type, use $ExpectType. To assert that an expression causes a compile error, use $ExpectError. (Assertions will be checked by the expect lint rule.)
(https://github.com/Microsoft/dtslint#write-tests)
import foo from 'lib-to-test';
foo(1);
foo(2);
foo('bar');
Adding $ExpectTypeSnapshot
Uses snapshot saved in file as expected type for expression.
Example:
foo.test.ts
const Foo = {
a: 1,
n: 17,
} as const;
By running eslint --fix
the following file will be created in the folder of foo.test.ts
:
__type-snapshots__/foo.test.ts.snap.json
By running eslint
snapshot type will be matched with actual type and Error will be emitted in case types don't match.
To create/update snapshots
eslint --fix
References
- https://github.com/gcanti/dtslint
- https://github.com/Microsoft/dtslint
- https://github.com/SamVerschueren/tsd
Appreciation
Many thanks to @ibezkrovnyi for creating the initial version and core infrastructure of this package! 💖