docs(linter): improve docs for eslint/getter-return (#6229)

This commit is contained in:
DonIsaac 2024-10-01 19:38:24 +00:00
parent d883562741
commit a949ecb052

View file

@ -16,7 +16,11 @@ use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;
use crate::{context::LintContext, rule::Rule, AstNode};
use crate::{
context::{ContextHost, LintContext},
rule::Rule,
AstNode,
};
fn getter_return_diagnostic(span: Span) -> OxcDiagnostic {
OxcDiagnostic::warn("Expected to always return a value in getter.")
@ -38,18 +42,39 @@ const METHODS_TO_WATCH_FOR: [(&str, &str); 4] = [
declare_oxc_lint!(
/// ### What it does
/// Requires all getters to have a return statement
///
/// Requires all getters to have a `return` statement.
///
/// ### Why is this bad?
/// Getters should always return a value. If they don't, it's probably a mistake.
///
/// This rule does not run on TypeScript files, since type checking will
/// catch getters that do not return a value.
///
/// ### Example
///
/// Examples of **incorrect** code for this rule:
/// ```javascript
/// class Person{
/// get name(){
/// class Person {
/// get name() {
/// // no return
/// }
/// }
///
/// const obj = {
/// get foo() {
/// // object getter are also checked
/// }
/// }
/// ```
///
/// Examples of **correct** code for this rule:
/// ```javascript
/// class Person {
/// get name() {
/// return this._name;
/// }
/// }
/// ```
GetterReturn,
nursery
@ -57,10 +82,6 @@ declare_oxc_lint!(
impl Rule for GetterReturn {
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
// https://eslint.org/docs/latest/rules/getter-return#handled_by_typescript
if ctx.source_type().is_typescript() {
return;
}
match node.kind() {
AstKind::Function(func) if !func.is_typescript_syntax() => {
self.run_diagnostic(node, ctx, func.span);
@ -81,6 +102,11 @@ impl Rule for GetterReturn {
Self { allow_implicit }
}
fn should_run(&self, ctx: &ContextHost) -> bool {
// https://eslint.org/docs/latest/rules/getter-return#handled_by_typescript
!ctx.source_type().is_typescript()
}
}
impl GetterReturn {
@ -494,4 +520,20 @@ fn test() {
Tester::new(GetterReturn::NAME, pass, fail)
.change_rule_path_extension("js")
.test_and_snapshot();
// TypeScript tests
let pass = vec![(
"var foo = {
get bar(): boolean | undefined {
if (Math.random() > 0.5) {
return true;
}
}
};",
None,
)];
let fail = vec![];
Tester::new(GetterReturn::NAME, pass, fail).test();
}