5
votes

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.

1
Have you looked at the GitHub repo? It has the source for all of the built-in rules? I think the best resource will be the TSLint source itself.cartant
Yes, but these rules are all quite simple - they all seem to do tree walking, not semantics. Could it be that one has to use the typescript NPM module to access semantic functionality? In this case I will update my question. What do you think?bloxx
@bloxx did you end up making any progress on this endeavour? I also feel let down by TypeScript for the same reasons, but I understand that trade-offs were made (as you can read here, if you haven't already: github.com/Microsoft/TypeScript/issues/9825).pleasedesktop
No, I did not, it felt like I was still missing some knowledge about how TypeScript works. As you said - I'd really enjoy stricter type checking rules but I also understand that that's a complicated topic and the TypeScript team has to look in all directions for inconsistencies (apart for bivariance, I think TypeScript's type system is more powerful than most other ones, I really like it...). Hmmm... Maybe I'll look at it again later.bloxx

1 Answers

4
votes

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.