Skip to content

feat(types): Add Exposed template to SetupContext #13177

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 9 commits into
base: main
Choose a base branch
from

Conversation

michaelcozzolino
Copy link

@michaelcozzolino michaelcozzolino commented Apr 8, 2025

This PR allows the possibility to type expose when using defineComponent with composition api

export const UseVirtualList = defineComponent(
  <T = any>(props: {msg: T}, { slots, expose }: SetupContext<EmitsOptions, SlotsType<{}>, { index: number }>,
  ) => {
        ...
        const index = 2
        expose({index})
})

I added the template wherever it would be needed.
i'm not sure if in packages/runtime-core/src/componentOptions.ts at line 142 it's needed as well, as i already see an Exposed template, but doesn't look like having the type for the one in SetupContext. let me know if everything is fine

Summary by CodeRabbit

  • New Features
    • Improved type safety for exposed properties in components defined with a setup function, allowing explicit control over which properties are accessible on the component instance.
  • Tests
    • Added new tests to verify correct typing and accessibility of properties exposed via the setup function, ensuring non-exposed properties are not accessible.

Copy link

github-actions bot commented Apr 9, 2025

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 100 kB 38.1 kB 34.4 kB
vue.global.prod.js 158 kB 58.3 kB 51.9 kB

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.4 kB 18.1 kB 16.6 kB
createApp 54.4 kB 21.2 kB 19.4 kB
createSSRApp 58.6 kB 22.9 kB 20.9 kB
defineCustomElement 59.2 kB 22.7 kB 20.7 kB
overall 68.5 kB 26.3 kB 24 kB

Copy link

pkg-pr-new bot commented Apr 9, 2025

Open in StackBlitz

@vue/compiler-core

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

@vue/compiler-dom

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

@vue/compiler-sfc

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

@vue/compiler-ssr

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

@vue/reactivity

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

@vue/runtime-core

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

@vue/runtime-dom

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

@vue/server-renderer

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

@vue/shared

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

vue

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

@vue/compat

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

commit: bd8c78d

@edison1105 edison1105 requested a review from jh-leong April 9, 2025 00:35
@jh-leong
Copy link
Member

jh-leong commented Apr 9, 2025

Thanks for the PR!

Could you please add test cases for this change in:

  • packages-private/dts-test/defineComponent.test-d.tsx
  • packages-private/dts-test/functionalComponent.test-d.tsx

This would help verify the type behavior.

@michaelcozzolino
Copy link
Author

Thanks for the PR!

Could you please add test cases for this change in:

  • packages-private/dts-test/defineComponent.test-d.tsx
  • packages-private/dts-test/functionalComponent.test-d.tsx

This would help verify the type behavior.

I added a test, but i was able to achieve the goal just partially, the expose keys seem to be typed properly, but the values are not typed at all, do you have any suggestions?

@edison1105
Copy link
Member

@michaelcozzolino
Could you please fix the test failing?

Copy link

coderabbitai bot commented Apr 26, 2025

Walkthrough

The changes introduce enhanced type safety and explicit typing for component property exposure in a component-based framework. New generic parameters are added to core types and function overloads to allow precise specification of which properties are exposed to component instances, both in options objects and setup functions. The test suite is expanded to verify that only explicitly exposed properties are accessible on component instances and that typings reflect these constraints. These adjustments impact type declarations for component definitions, setup contexts, and functional components, supporting stricter and more expressive public API contracts.

Changes

File(s) Change Summary
packages/runtime-core/src/apiDefineComponent.ts Added a generic parameter Exposed to DefineSetupFnComponent and related defineComponent overloads. Updated the setup function context and return types to reflect exposed properties, and allowed explicit exposure via an expose array in the options object.
packages/runtime-core/src/component.ts Introduced a generic Exposed parameter to FunctionalComponent and an expose property for explicit exposure. Generalized the SetupContext type and its expose method to allow more precise typing of exposed properties.
packages-private/dts-test/defineComponent.test-d.tsx Renamed the "expose typing" test suite to "expose typing w/ options object". Added a new test suite "expose typing w/ setup function" to verify that only explicitly exposed properties are accessible on the component instance and that typings are enforced accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Component
    participant SetupFunction
    participant Instance

    User->>Component: defineComponent({ setup(ctx) { ctx.expose({a, b}) } })
    Component->>SetupFunction: Call setup with SetupContext (expose method)
    SetupFunction->>SetupFunction: Call ctx.expose({a, b})
    SetupFunction-->>Component: Return setup result
    Component->>Instance: Create instance with exposed properties a, b
    User->>Instance: Access instance.a / instance.b (allowed)
    User->>Instance: Access instance.c (TypeScript error)
Loading

Poem

In the warren of types, a new tunnel appears,
Where only the chosen are seen by your peers.
Expose with precision, let typings be tight,
Now bunnies and coders can sleep well at night.
With setup and options, the contract is clear—
Only what’s exposed shall ever hop near! 🐇✨


📜 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 a23fb59 and 3f6d453.

📒 Files selected for processing (3)
  • packages-private/dts-test/defineComponent.test-d.tsx (2 hunks)
  • packages/runtime-core/src/apiDefineComponent.ts (3 hunks)
  • packages/runtime-core/src/component.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages-private/dts-test/defineComponent.test-d.tsx (3)
packages/runtime-core/src/apiDefineComponent.ts (1)
  • defineComponent (327-337)
packages/runtime-core/src/componentEmits.ts (1)
  • EmitsOptions (41-41)
packages/runtime-core/src/index.ts (1)
  • h (109-109)
packages/runtime-core/src/apiDefineComponent.ts (5)
packages/runtime-core/src/component.ts (2)
  • SetupContext (280-291)
  • ComponentOptions (275-275)
packages/runtime-core/src/index.ts (10)
  • SetupContext (262-262)
  • RenderFunction (281-281)
  • ComponentOptions (276-276)
  • DefineSetupFnComponent (272-272)
  • EmitsToProps (294-294)
  • PublicProps (273-273)
  • defineComponent (63-63)
  • EmitsOptions (292-292)
  • SlotsType (314-314)
  • ComponentObjectPropsOptions (319-319)
packages/runtime-core/src/componentOptions.ts (2)
  • RenderFunction (108-108)
  • ComponentOptions (239-294)
packages/runtime-core/src/componentEmits.ts (2)
  • EmitsToProps (43-58)
  • EmitsOptions (41-41)
packages/runtime-core/src/componentProps.ts (1)
  • ComponentObjectPropsOptions (47-49)
🪛 Biome (1.9.4)
packages-private/dts-test/defineComponent.test-d.tsx

[error] 1643-1643: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)

packages/runtime-core/src/apiDefineComponent.ts

[error] 138-138: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 139-139: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 180-180: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 182-182: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🔇 Additional comments (10)
packages-private/dts-test/defineComponent.test-d.tsx (1)

1640-1673: Well designed type test for exposed properties in the setup context.

This new test suite effectively validates the typing enhancements for the expose function in the setup context. It properly verifies that:

  1. Properties explicitly exposed via expose({ a, b }) are correctly typed on the component instance
  2. Non-exposed properties (like c) are correctly flagged as type errors when accessed
  3. The type system properly enforces the constraints defined in the SetupContext generic parameter

The test ensures that developers get proper type checking when using the expose feature with setup functions, improving type safety.

🧰 Tools
🪛 Biome (1.9.4)

[error] 1643-1643: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)

packages/runtime-core/src/component.ts (4)

220-221: Good enhancement to FunctionalComponent interface typing.

Adding the Exposed generic parameter to FunctionalComponent is a sensible enhancement that provides type safety for exposed properties on component instances. The default of Record<string, any> maintains backward compatibility.


230-231: Properly typed property for exposed keys.

The addition of the expose?: (keyof Exposed)[] property aligns with the new generic parameter, allowing proper typing of which properties are exposed on the component instance.


283-284: Well-designed generic parameter for SetupContext.

The new EX generic parameter for SetupContext is a good addition that enables type safety for exposed properties. Using Record<string, any> as default maintains backward compatibility.


289-290: Improved type safety for the expose method.

The enhanced signature for the expose method now properly types the exposed properties, ensuring that only properties of the correct type can be exposed. The generic parameter <Exposed extends EX = EX> allows for flexibility while maintaining type safety.

packages/runtime-core/src/apiDefineComponent.ts (5)

121-122: Good addition of Exposed generic parameter to DefineSetupFnComponent.

Adding the Exposed generic parameter to DefineSetupFnComponent properly extends the type system to track exposed properties at the component type level. This change aligns well with Vue's existing type patterns.


137-141: Correct propagation of generics to CreateComponentPublicInstanceWithMixins.

The updates to the CreateComponentPublicInstanceWithMixins parameters correctly pass the Exposed generic parameter to the public instance type, ensuring that component instances will be properly typed with only the exposed properties.

🧰 Tools
🪛 Biome (1.9.4)

[error] 138-138: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 139-139: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


158-163: Well-coordinated type enhancements for defineComponent.

Adding the Exposed generic parameter to the defineComponent overloads and updating the setup function's context parameter to use SetupContext<E, S, Exposed> ensures proper type propagation throughout the API. This creates a consistent typing experience when using the expose function.


168-169: Good addition of typed expose option.

Adding the typed expose?: (keyof Exposed)[] option properly connects the exposed property types to the component options, enabling type checking for the exposed properties.


175-177: Well-designed return type for exposed properties.

Using Extract<keyof Exposed, string> in the return type correctly ensures that only string keys from the exposed properties are used in the component instance type. This maintains type safety while allowing flexible property types.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants