简体   繁体   English

自定义TSLint规则检查函数参数可赋值性(无双变量)

[英]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: https://www.typescriptlang.org/docs/handbook/type-compatibility.html#function-parameter-bivariance 我只是偶然发现TypeScript并不是非常严格地检查函数的可赋值性: 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: 所以我想知道是否有可能建立一个自定义TSLint规则告诉我何时做这样的事情:

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. 但是,有关创建自定义TSLint规则的文档似乎相当不完整,我只找到了一个纯语法检查的单个示例。 I would be really happy if you could advise me a resource to learn how to extend TSLint with semantic rules like this one. 如果您能告诉我一个资源来学习如何使用像这样的语义规则来扩展TSLint,我将非常高兴。

When looking to implement a custom rule, the TSLint source code is a useful resource for guidance. 在寻求实现自定义规则时,TSLint源代码是一个有用的指导资源。 The source for all of the built-in rules is available in the TSLint repo . TSLint仓库中提供了所有内置规则的源代码。 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 . 这些规则使用ProgramAwareRuleWalker ,它通过TypeChecker使规则可以使用类型信息。

There is some information on how the TypeChecker can be used in the TypeScript Compiler API documenation . 对于如何将一些信息TypeChecker可以在使用打字稿编译器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. 如果启用了使用ProgramAwareRuleWalker规则,则必须使用--type-check选项运行--type-check并且还必须指定--project

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM