bloxx bloxx - 1 year ago 192
TypeScript Question

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

I just stumbled upon the fact that TypeScript isn't quite strict checking the assignability of functions:

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.

Answer Source

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:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download