Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom TSLint rule to check function parameter assignability (no bivariance)

Tags:

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.

like image 689
bloxx Avatar asked Aug 21 '16 22:08

bloxx


1 Answers

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:

  • the no-for-in-array rule; and
  • the restrict-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.

like image 185
cartant Avatar answered Sep 22 '22 16:09

cartant