Skip to content

fix(types): restrict provide() key to string | InjectionKey to avoid unexpected key collisions #12999

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

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

Conversation

et84121
Copy link

@et84121 et84121 commented Mar 5, 2025

fix #9439

Overview

This PR updates the type signature of the provide() function to accept only two kinds of keys:

  1. InjectionKey<T> (which is a symbol), and
  2. string

Previously, provide() accepted keys of type number or even object. In JavaScript, any non-string, non-symbol key will be implicitly converted to a string. For example:

  • A number key like 123 becomes the string "123".
  • An object key becomes the string "[object Object]".

These conversions can cause key collisions. Multiple different objects (or numbers, booleans, etc.) might all end up converting to the same string key, overwriting each other’s values. That is obviously unwanted behavior in an API designed for unique injection keys.

Reasoning

  1. Type Consistency: Restricting keys to string | symbol is consistent with core JavaScript behavior for object property names – objects use string or symbol keys.
  2. Prevent Unintended Collisions: Implicit string conversion of numbers, booleans, or objects can lead to subtle bugs. For instance, two different objects would both become "[object Object]".
  3. Align with Usage: In typical Vue usage, injection keys are often symbol-based to ensure uniqueness, or occasionally string-based for clarity. Accepting arbitrary key types can mask potential errors.

What Changed

  • In apiInject.ts, the type of provide() is changed from:
    export function provide<T, K = InjectionKey<T> | string | number>(key: K, ...)
    to:
    export function provide<T, K extends InjectionKey<T> | string = InjectionKey<T> | string>(
      key: K,
      ...
    )
    This enforces that key must be either a symbol-based InjectionKey<T> or a string, eliminating number (and others) from the accepted set of types.

Benefits

  • Stronger Type Safety: Prevents accidental usage of boolean, object, or number as keys that silently collide after string conversion.
  • Clearer Intent: Makes it explicit that injection keys should be unique symbols or well-defined strings.
  • Future-proof: Matches the standard practice in JavaScript/TypeScript of using string | symbol for object keys, avoiding inconsistent usage.

Overall, this change ensures safer and more predictable behavior when injecting or providing dependencies in Vue, reducing the risk of subtle collisions and bugs.

External Document

Summary by CodeRabbit

  • Bug Fixes
    • Improved type safety for the provide function, ensuring only valid key types are accepted.
  • Tests
    • Updated type tests to explicitly mark and clarify invalid usages of the provide function.

@skirtles-code
Copy link
Contributor

@edison1105
Copy link
Member

/ecosystem-ci run

Copy link

pkg-pr-new bot commented Mar 6, 2025

Open in Stackblitz

@vue/compiler-core

npm i https://pkg.pr.new/@vue/compiler-core@12999

@vue/compiler-dom

npm i https://pkg.pr.new/@vue/compiler-dom@12999

@vue/compiler-sfc

npm i https://pkg.pr.new/@vue/compiler-sfc@12999

@vue/compiler-ssr

npm i https://pkg.pr.new/@vue/compiler-ssr@12999

@vue/reactivity

npm i https://pkg.pr.new/@vue/reactivity@12999

@vue/runtime-core

npm i https://pkg.pr.new/@vue/runtime-core@12999

@vue/runtime-dom

npm i https://pkg.pr.new/@vue/runtime-dom@12999

@vue/server-renderer

npm i https://pkg.pr.new/@vue/server-renderer@12999

@vue/shared

npm i https://pkg.pr.new/@vue/shared@12999

vue

npm i https://pkg.pr.new/vue@12999

@vue/compat

npm i https://pkg.pr.new/@vue/compat@12999

commit: 361d108

Copy link

github-actions bot commented Mar 6, 2025

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 100 kB 38.1 kB 34.3 kB
vue.global.prod.js 158 kB 58 kB 51.6 kB

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.5 kB 18.2 kB 16.7 kB
createApp 54.6 kB 21.3 kB 19.4 kB
createSSRApp 58.8 kB 23 kB 21 kB
defineCustomElement 59.4 kB 22.9 kB 20.8 kB
overall 68.6 kB 26.4 kB 24.1 kB

@vue-bot
Copy link
Contributor

vue-bot commented Mar 6, 2025

📝 Ran ecosystem CI: Open

suite result latest scheduled
language-tools failure success
nuxt success success
pinia failure success
primevue failure success
quasar success success
radix-vue success success
router success success
test-utils success success
vant success success
vite-plugin-vue success success
vitepress success success
vue-i18n success success
vue-macros success success
vuetify success success
vueuse failure success
vue-simple-compiler success success

@edison1105
Copy link
Member

/ecosystem-ci run

@vue-bot
Copy link
Contributor

vue-bot commented Mar 7, 2025

📝 Ran ecosystem CI: Open

suite result latest scheduled
language-tools success success
vitepress success success
nuxt success success
primevue success success
pinia success success
vue-i18n success success
quasar success success
radix-vue success success
test-utils success success
vite-plugin-vue success success
vue-macros success success
vuetify success success
router success success
vueuse failure success
vue-simple-compiler success success
vant success success

@edison1105 edison1105 added the ready to merge The PR is ready to be merged. label Mar 7, 2025
Copy link

coderabbitai bot commented Jul 12, 2025

Walkthrough

The changes update the type constraints for the provide function in the core runtime, removing support for number as a valid key type. Corresponding type tests are updated to expect errors when using number or other invalid key types, and a redundant invalid test case is removed. No changes are made to runtime logic.

Changes

File(s) Change Summary
packages/runtime-core/src/apiInject.ts Restricts provide key type to `InjectionKey
packages-private/dts-test/inject.test-d.ts Adds @ts-expect-error for invalid provide key types and removes a redundant invalid test case.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant provide (apiInject.ts)
    User->>provide (apiInject.ts): provide(key: InjectionKey<T> | string, value: T)
    Note right of provide (apiInject.ts): Compile-time error if key is not InjectionKey<T> or string
Loading

Assessment against linked issues

Objective Addressed Explanation
Support number as a valid key type for inject/provide (#9439) The code explicitly removes number as a valid key type, which is contrary to the objective.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Removal of provide<Cube>(123, { size: 123 }) test (packages-private/dts-test/inject.test-d.ts) This removal is not directly related to the objective of supporting number as a key type.

Poem

In the warren of code, a rabbit did peek,
At provide's new rules, so tidy and sleek.
"No numbers!" it cried, "only keys of the string!"
Type errors now dance, as the type checkers sing.
With paws on the keyboard, I hop and I cheer—
For type safety's here, and the code is now clear!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 347ef1d and 8d0d413.

📒 Files selected for processing (2)
  • packages-private/dts-test/inject.test-d.ts (1 hunks)
  • packages/runtime-core/src/apiInject.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages-private/dts-test/inject.test-d.ts (1)
packages/runtime-core/src/apiInject.ts (1)
  • provide (10-33)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
🔇 Additional comments (3)
packages/runtime-core/src/apiInject.ts (1)

10-13: LGTM! Type restriction effectively prevents key collisions.

The updated type signature correctly restricts the key parameter to InjectionKey<T> | string only, preventing potential key collisions that could occur when numbers, booleans, or objects are implicitly converted to strings. This aligns perfectly with JavaScript's object key behavior and improves type safety while maintaining runtime compatibility.

packages-private/dts-test/inject.test-d.ts (2)

14-15: Correctly validates type error for numeric keys.

The @ts-expect-error annotation properly tests that numeric keys are now rejected by the type system, preventing potential key collision bugs.


16-18: Comprehensive test coverage for boolean and string keys.

The test correctly expects type errors for boolean keys while allowing string keys to pass. This validates that the type restriction works as intended - rejecting collision-prone types while preserving valid usage patterns.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Types inject does not support number argument
4 participants