I just stumbled upon the fact that TypeScript isn't quite strict checking the assignability of functions: https://www.typescriptlang.org/docs/handbook/type-compatibility.html#function-parameter-bivariance
Unfortunately, for some patterns parameter bivariance misses important type checking. So I'm wondering whether it would be possible to build a custom TSLint rule telling me when I'm doing something like this:
interface Base {}
interface BaseEx extends Base { x; }
let fn1: (a: Base) => void;
let fn2: (b: BaseEx) => void;
fn1 = fn2; // TSLint: parameter (a: BaseEx) is not assignable to (b: Base)
However, documentation on creating custom TSLint rules seems rather incomplete, I only found a single example of a purely syntactical check. I would be really happy if you could advise me a resource to learn how to extend TSLint with semantic rules like this one.
When looking to implement a custom rule, the TSLint source code is a useful resource for guidance. The source for all of the built-in rules is available in the TSLint repo. Most of the rules to not require access to type information. However, there are two that do:
no-for-in-array
rule; andrestrict-plus-operands
rule.Those rules use the ProgramAwareRuleWalker
, which makes type information available to the rule via the TypeChecker
.
There is some information on how the TypeChecker
can be used in the TypeScript Compiler API documenation.
If rules that use the ProgramAwareRuleWalker
are enabled, TSLint must be run with the --type-check
option and a --project
must be specified, too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With