💼 This rule is enabled in the ✅ recommended
config.
🔧 This rule is automatically fixable by the --fix
CLI option.
💭 This rule requires type information.
Enforces that types indicated in special comments match the types of code values.
Types are compared with "display" checking: a direct string comparison between their actual type and the string comment or snapshot. See issue #18 for discussion around a new assertion for "assignability" checking.
The following kinds of comments are supported:
Twoslash annotations are comment lines that start with two slashes (// ) and the ^? identifier to annotate a type below a value in code. For example:
declare const getTextLength: (text: string) => number;
getTextLength("abc");
// ^? number
getTextLength;
// ^? (text: string) => number
Mismatching the type will cause a lint report:
"abc";
// ^? number
Expected type to be: number, got: string
Multiline type annotations are also supported:
const vector = {
x: 3,
y: 4,
};
vector;
// ^? const vector: {
// x: number;
// y: number;
// }
Place this above a line of code to assert that it causes a TypeScript type error.
For example:
// $ExpectError
const value: number = "abc";
⚠️ $ExpectError
does not suppress TypeScript type errors. Only TypeScript comment directives such as// @ts-expect-error
may do that. See #65.
A comment containing // $ExpectType
and a type, placed above or on a line of code.
It asserts that the value of the line of code is of that type.
For example:
declare const getTextLength: (text: string) => number;
// $ExpectType number
getTextLength("abc");
// $ExpectType (text: string) => number
getTextLength;
Mismatching the type will cause a lint report:
// $ExpectType number
"abc";
Expected type to be: number, got: string
Similar to $ExpectType
, but instead of a type, takes in a unique ID for a snapshot.
The snapshot will then be saved in a __type-snapshots__/*.snap.json
file alongside the original *
-named source file.
For example, given a file.ts
:
declare const getTextLength: (text: string) => number;
// $ExpectTypeSnapshot FunctionCallExpression
getTextLength("abc");
// $ExpectTypeSnapshot FunctionIdentifier
getTextLength;
...a __type-snapshots__/file.ts.snap.json
file will be created containing:
{
"FunctionCallExpression": "number",
"FunctionIdentifier": "(text: string) => number"
}
These snapshots will automatically update whenever eslint --fix
is run.
⚠️ #115: There are known issues around detecting whether to automatically update snapshots. Editor extensions are likely to not apply updates automatically. Try running ESLint with--fix
on the command-line, or failing that, manually updating.
Whether to disable $ExpectTypeSnapshot
auto-fixing.
Defaults to false
.