From 8b63eb353894c432f85c313d79e0c175fe3e2441 Mon Sep 17 00:00:00 2001 From: igm Date: Mon, 12 Jan 2026 13:48:13 +0800 Subject: [PATCH] Add ast-grep rule to prevent String() function usage Prefer .toString() or .toLocaleString() over String() for more predictable behavior and consistency. Co-Authored-By: Claude Opus 4.5 --- .../no-string-function-snapshot.yml | 20 +++++++++++++++++++ .../rule-tests/no-string-function-test.yml | 13 ++++++++++++ .ast-grep/rules/no-string-function.yml | 7 +++++++ 3 files changed, 40 insertions(+) create mode 100644 .ast-grep/rule-tests/__snapshots__/no-string-function-snapshot.yml create mode 100644 .ast-grep/rule-tests/no-string-function-test.yml create mode 100644 .ast-grep/rules/no-string-function.yml diff --git a/.ast-grep/rule-tests/__snapshots__/no-string-function-snapshot.yml b/.ast-grep/rule-tests/__snapshots__/no-string-function-snapshot.yml new file mode 100644 index 0000000..e9713eb --- /dev/null +++ b/.ast-grep/rule-tests/__snapshots__/no-string-function-snapshot.yml @@ -0,0 +1,20 @@ +id: no-string-function +snapshots: + String(123): + labels: + - source: String(123) + style: primary + start: 0 + end: 11 + String(Date.now()): + labels: + - source: String(Date.now()) + style: primary + start: 0 + end: 18 + String(value): + labels: + - source: String(value) + style: primary + start: 0 + end: 13 diff --git a/.ast-grep/rule-tests/no-string-function-test.yml b/.ast-grep/rule-tests/no-string-function-test.yml new file mode 100644 index 0000000..814c8dd --- /dev/null +++ b/.ast-grep/rule-tests/no-string-function-test.yml @@ -0,0 +1,13 @@ +id: no-string-function +valid: + # toString() is fine + - value.toString() + - (123).toString() + - date.toLocaleString() + # Other functions named String are fine + - myString(value) +invalid: + # String() function should be flagged + - String(value) + - String(123) + - String(Date.now()) diff --git a/.ast-grep/rules/no-string-function.yml b/.ast-grep/rules/no-string-function.yml new file mode 100644 index 0000000..10044df --- /dev/null +++ b/.ast-grep/rules/no-string-function.yml @@ -0,0 +1,7 @@ +id: no-string-function +language: typescript +severity: error +message: "Don't use String() - use .toString() or .toLocaleString() instead." +note: "String() can have unexpected behavior. Use .toString() for general conversion or .toLocaleString() for locale-aware formatting." +rule: + pattern: String($VAL)