Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(utils): resolve common function ts error #2903

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from

Conversation

wuyiping0628
Copy link
Collaborator

@wuyiping0628 wuyiping0628 commented Feb 17, 2025

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • Refactor
    • Improved flexibility by allowing optional parameters across key operations.
    • Enhanced type safety and consistency in validations, error handling, and asynchronous processes.
  • Chores
    • Updated configuration settings for a more robust development experience.

@wuyiping0628 wuyiping0628 added the enhancement New feature or request (功能增强) label Feb 17, 2025
Copy link

coderabbitai bot commented Feb 17, 2025

Walkthrough

The pull request updates several utility files by enhancing type safety and flexibility. In the tree model and validation modules, optional parameters have been introduced to method signatures and function parameters modified to accept objects. Type annotations have been added or refined across upload, schema, and utility functions. Additionally, minor logic adjustments (such as converting numbers to strings during formatting) have been made without altering core functionality. Finally, a new TypeScript compiler option ("noImplicitAny": false) has been added.

Changes

File(s) Change Summary
packages/utils/src/tree-model/node.ts Made index and batch parameters optional in the insertChild method.
packages/utils/src/upload-ajax/index.ts Added explicit type annotations for the error variable and the event parameter in the progress event callback.
packages/utils/src/validate/rules/required.ts
packages/utils/src/validate/rules/type.ts
Introduced a new RequiredType interface and updated validation functions to use explicit object-based parameter passing.
packages/utils/src/validate/schema.ts Made the translate parameter optional and added type assertions for variables (e.g., errors, fields, finalErrors, callbacks, validators, messages) in various functions.
packages/utils/src/validate/util.ts Changed the %d case in format to return a string; made the dataType parameter in isEmptyValue optional; updated type assertions for result arrays and the promise return type in asyncMap.
packages/utils/src/validate/validations/pattern.ts Updated the declaration of the errors array to explicitly assert it as an array of any type (any[]).
packages/utils/tsconfig.json Added the compiler option "noImplicitAny": false within compilerOptions.

Suggested reviewers

  • zzcr

Poem

I'm a little rabbit hopping through the code,
With optional params dancing in every node.
Type annotations bloom in fields so bright,
Validations sing in the soft moonlight.
I nibble on clean code with a joyful heart—
Each change is a carrot, a work of art! 🐇

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/utils/src/tree-model/node.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-vue".

(The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-vue@latest --save-dev

The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

packages/utils/src/upload-ajax/index.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-vue".

(The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-vue@latest --save-dev

The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

packages/utils/src/validate/schema.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-vue".

(The package "eslint-plugin-vue" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-vue@latest --save-dev

The plugin "eslint-plugin-vue" was referenced from the config file in ".eslintrc.js » @antfu/eslint-config » @antfu/eslint-config-vue".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

  • 4 others
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Walkthrough

This pull request addresses TypeScript errors in common utility functions by adding type annotations and interfaces. It enhances type safety and resolves existing issues without introducing breaking changes.

Changes

Files Changed Summary
packages/utils/src/tree-model/node.ts Added optional parameters to insertChild function.
packages/utils/src/upload-ajax/index.ts Added type annotations for error and event objects.
packages/utils/src/validate/rules/required.ts Introduced RequiredType interface for function parameters.
packages/utils/src/validate/rules/type.ts Modified function call to use an object with named parameters.
packages/utils/src/validate/schema.ts Added optional parameters and type annotations for various functions and objects.
packages/utils/src/validate/util.ts Added type annotations and optional parameters to utility functions.
packages/utils/src/validate/validations/pattern.ts Added type annotations for error arrays.
packages/utils/tsconfig.json Updated TypeScript configuration.

const deep = isDeep(rule, data)

failds = arrayed(failds)

if (!options.suppressWarning && failds.length) {
Schema.warning('async-validator:', failds)
Schema.warning()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The removal of the async-validator: prefix in the Schema.warning call may lead to loss of context in log messages. Consider maintaining the prefix or ensuring that the logging mechanism provides sufficient context.

Copy link

[e2e-test-warn]
The component to be tested is missing.

The title of the Pull request should look like "fix(vue-renderless): [action-menu, alert] fix xxx bug".

Please make sure you've read our contributing guide

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (7)
packages/utils/src/validate/rules/required.ts (1)

16-23: LGTM! Well-structured interface definition.

The RequiredType interface clearly defines the expected parameter types and correctly marks optional parameters.

Consider adding JSDoc comments to document the purpose of each interface property.

packages/utils/src/upload-ajax/index.ts (2)

41-41: Consider using a more specific type instead of any.

The error variable could use a more specific type like Error & { status?: number; method?: string; url?: string } to better represent its structure.

-  const error: any = new Error(errorText)
+  const error: Error & { status?: number; method?: string; url?: string } = new Error(errorText)

59-59: Use ProgressEvent type instead of any.

The event parameter should use the built-in ProgressEvent type for better type safety.

-    xhr.upload.onprogress = (event: any) => {
+    xhr.upload.onprogress = (event: ProgressEvent) => {
packages/utils/src/validate/util.ts (2)

112-112: Consider documenting the default behavior.

Making dataType optional is good, but please document the default behavior when it's not provided.

Add JSDoc comment explaining the default behavior:

+/**
+ * @param data The value to check for emptiness
+ * @param dataType Optional type of the data. If not provided, only null check is performed
+ */
 export function isEmptyValue(data, dataType?) {

138-138: Use more specific types instead of any[].

Consider using more specific types for the arrays based on their content.

-  const results = [] as any[]
+  interface ValidationError {
+    field: string;
+    message: string;
+  }
+  const results = [] as ValidationError[]

Also applies to: 186-186, 224-224

packages/utils/src/validate/schema.ts (1)

16-16: Consider using proper TypeScript interfaces instead of optional parameters.

Instead of making translate optional, consider creating an interface for the Schema constructor parameters to better document the expected types.

+interface SchemaOptions {
+  descriptor: any;
+  translate?: any;
+}

-function Schema(descriptor, translate?) {
+function Schema(options: SchemaOptions) {
+  const { descriptor, translate } = options;
packages/utils/tsconfig.json (1)

15-15:

❓ Verification inconclusive

Consider keeping noImplicitAny enabled for better type safety.

Disabling noImplicitAny reduces TypeScript's ability to catch potential type-related bugs. While this might help with initial TypeScript adoption, consider:

  1. Keeping it enabled and properly typing variables
  2. Using explicit any type annotations where absolutely necessary
  3. Creating a migration plan to gradually remove implicit any usage

🌐 Web query:

What are the benefits of enabling noImplicitAny in TypeScript?

💡 Result:

Enabling the noImplicitAny compiler option in TypeScript significantly improves code quality and safety by enforcing stricter type checks. Here are its key benefits:

1. Prevents accidental any type inference

  • Catches cases where TypeScript would silently default variables/parameters to any when types can't be inferred[2][4]
  • Forces explicit type annotations for untyped function parameters and variables[1][3]

Example of prevented error:

// Without noImplicitAny: Compiles but risks runtime errors
function splitString(input) {  // input implicitly 'any'
  return input.split('.');
}

// With noImplicitAny: Triggers compile-time error
function splitString(input) {  // 🚨 Error: Parameter 'input' implicitly has 'any' type
  return input.split('.');
}

2. Enhances type safety

  • Reduces runtime errors by catching type mismatches during compilation[3][6]
  • Helps identify areas needing proper type declarations during refactoring[7]
  • Prevents dangerous operations on any-typed values[3][6]

3. Improves code maintainability

  • Creates self-documenting code through explicit type annotations[1][3]
  • Makes type-related issues visible during development rather than at runtime[2][4]
  • Facilitates safer code evolution by surfacing breaking API changes[7]

4. Encourages better type practices

  • Promotes use of proper types instead of any escape hatches[6][9]
  • Guides developers toward TypeScript's full type system capabilities[3][6]
  • Works well with other strict mode flags for comprehensive type checking[8]

Comparison table of enabled vs disabled:

Scenario noImplicitAny: false noImplicitAny: true
Untyped function param Silently becomes any Compile-time error
Missing return type Inferred as any Error if can't be inferred
Third-party JS imports Implicit any allowed Requires type declarations[1]

While enabling noImplicitAny may initially require adding type annotations[1][9], it leads to more robust and maintainable TypeScript code in the long term by eliminating hidden type assumptions and preventing entire classes of runtime errors[2][4].

Citations:


Action: Re-assess the decision to disable noImplicitAny (see packages/utils/tsconfig.json, line 15)

Disabling noImplicitAny can undermine TypeScript’s strict type-checking, allowing implicit any types that could lead to runtime bugs and reduced code clarity. Enabling noImplicitAny offers significant benefits by enforcing explicit type annotations and catching potential type mismatches early. If a gradual adoption is required, please consider the following:

  • Re-enable noImplicitAny to leverage TypeScript’s compiler benefits and improve overall code safety.
  • Adopt explicit any only where absolutely necessary to minimize unintended type omissions.
  • Develop a clear migration plan to phase out implicit any usage over time while maintaining robust type-checking.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 441c376 and 91d9e3b.

📒 Files selected for processing (8)
  • packages/utils/src/tree-model/node.ts (1 hunks)
  • packages/utils/src/upload-ajax/index.ts (2 hunks)
  • packages/utils/src/validate/rules/required.ts (1 hunks)
  • packages/utils/src/validate/rules/type.ts (1 hunks)
  • packages/utils/src/validate/schema.ts (7 hunks)
  • packages/utils/src/validate/util.ts (6 hunks)
  • packages/utils/src/validate/validations/pattern.ts (1 hunks)
  • packages/utils/tsconfig.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/utils/src/validate/validations/pattern.ts
🔇 Additional comments (4)
packages/utils/src/validate/rules/type.ts (1)

88-89: LGTM! Good refactoring to use object parameters.

The change to use object parameters improves code maintainability and aligns with the new RequiredType interface.

packages/utils/src/validate/util.ts (2)

70-70: LGTM! Explicit toString() conversion is safer.

Using explicit toString() conversion is safer than implicit type coercion.


200-201: LGTM! Good addition of Promise type annotations.

The explicit Promise<void> type annotations improve code clarity and type safety.

Also applies to: 225-226

packages/utils/src/tree-model/node.ts (1)

281-281: LGTM! Optional parameters improve API flexibility.

Making index and batch parameters optional is a good improvement as it allows for more flexible usage of the insertChild method while maintaining backward compatibility.

Comment on lines +33 to +34
let errors = [] as any
let fields = {} as any
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Replace any type assertions with proper types.

Using any type assertions reduces type safety. Consider defining proper interfaces for these variables.

-let errors = [] as any
-let fields = {} as any
+interface ValidationError {
+  field: string;
+  message: string;
+}
+interface ValidationFields {
+  [key: string]: ValidationError[];
+}
+let errors: ValidationError[] = []
+let fields: ValidationFields = {}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let errors = [] as any
let fields = {} as any
interface ValidationError {
field: string;
message: string;
}
interface ValidationFields {
[key: string]: ValidationError[];
}
let errors: ValidationError[] = []
let fields: ValidationFields = {}

Comment on lines +388 to +394
Schema.validators = {} as any

Schema.warning = warning

Schema.messages = {}
Schema.messages = {} as any

Schema.systemMessages = {}
Schema.systemMessages = {} as any
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Define proper types for Schema static properties.

Using any type assertions for static properties reduces type safety. Consider defining proper interfaces.

+interface Validators {
+  [key: string]: (rule: any, value: any, callback: Function, source: any, options: any) => void;
+}
+interface Messages {
+  [key: string]: string;
+}

-Schema.validators = {} as any
-Schema.messages = {} as any
-Schema.systemMessages = {} as any
+Schema.validators: Validators = {}
+Schema.messages: Messages = {}
+Schema.systemMessages: Messages = {}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Schema.validators = {} as any
Schema.warning = warning
Schema.messages = {}
Schema.messages = {} as any
Schema.systemMessages = {}
Schema.systemMessages = {} as any
interface Validators {
[key: string]: (rule: any, value: any, callback: Function, source: any, options: any) => void;
}
interface Messages {
[key: string]: string;
}
Schema.validators: Validators = {}
Schema.warning = warning
Schema.messages: Messages = {}
Schema.systemMessages: Messages = {}

@@ -85,7 +85,8 @@ const types = {

export default function (rule, value, source, errors, options) {
if (rule.required && value === undefined) {
required(rule, value, source, errors, options)
let checkValue = value
required({ rule, checkValue, source, errors, options })
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这样改有问题吧,原本是五个参数,改之后变成一个参数了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request (功能增强)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants