8000 fix(types): make generics with runtime props in defineComponent work (fix #11374) by danyadev · Pull Request #13119 · vuejs/core · GitHub
[go: up one dir, main page]

Skip to content

fix(types): make generics with runtime props in defineComponent work (fix #11374) #13119

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

Conversation

danyadev
Copy link
@danyadev danyadev commented Mar 30, 2025

fixes #11374
relates to #12761 (comment), #7963 (comment)

Problem

The "support" for generics in defineComponent was introduced in #7963, but it simply doesn't work: when you pass the props option, TypeScript ignores the main props definition and infers the props type from the props option instead.

Unfortunately, this option doesn't provide any useful type hints except for the names of the props, so all the props become any

Here is a simple example, where instead of expected normal types we encounter any:

https://play.vuejs.org/#eNp9Ustu2zAQ/JUFL1IAQ0bR9qLKAtogh/bQBIlvYRAY0lphQi8FklIcCPr3LCnLeSIniTO7s7OPQfxu26zvUOSicJVVrQe9oWYlhXd7KUpJatca62GAGreK8NTwm5A8jLC1ZgcJZye/JEnyTy3ChTWtK9YlrGCQBOBQY+WxzmEdnoZO71gfc0hN65Uhxk9gVUJvVC1pDDqVIefhKiayzLu6abEG3Huk2oHzVlFTpm0omh9rR8FY3aLvLEEakaJWffniZ4hZ2QyMxTLw7GEx5R5Er5M5IllAMvtPbjjwJLjFfZwPu9x0On7fuJ1KfzSTBgQmT9MvPw49zwV5C1tjpDhObTWkMxdFwqSMxkyb5oUYYXlQnDsCYKfBbbGcdsyYWPCGOX+rmuzeGeIDiCalqNi70mjP436cFDyqSU+Kjdbm8V/EvO1wMePVHVYPn+D34Yhy/rmw6ND2KMWR8xvboJ/os6v/vNNX5M7UneboL8hL5N674HEK+9NRzbZfxUW3f+P98pms3Vk4Gzc3FYyGSL65kadx26MNHA/ie/Yz+/ZDjM+7YwkP

type Props<T> = {
  selected: T
  onChange: (option: T) => void
}

const Select = defineComponent(<T extends string>(props: Props<T>) => {
  return () => <div>selected: {props.selected}</div>
}, {
  props: ['selected', 'onChange']
})

Solution

Let's look at one of the overloads of defineComponent:

export function defineComponent<
  Props extends Record<string, any>,
  E extends EmitsOptions = {},
  EE extends string = string,
  S extends SlotsType = {},
>(
  setup: (
    props: Props,
    ctx: SetupContext<E, S>,
  ) => RenderFunction | Promise<RenderFunction>,
  options?: Pick<ComponentOptions, 'name' | 'inheritAttrs'> & {
    props?: (keyof Props)[]
    emits?: E | EE[]
    slots?: S
  },
): DefineSetupFnComponent<Props, E, S>

Here we can see the Props generic type, the setup argument using Props and the options argument also using Props

When we add a generic type to the setup function, it becomes less obvious for TypeScript to decide which variable to use to infer the generic type, and unfortunately for us it chooses the variant with less type density.

So we need to tell TypeScript not to infer Props from the options.props field:

props?: (keyof NoInfer<Props>)[]

Another solution

Initially I've come up with another solution which doesn't rely on that new TypeScript NoInfer type. But as you already use NoInfer in runtime code, it may be irrelevant.

It works by separating Props into two generics — original Props and DeclaredProps — and using them differently:

export function defineComponent<
  Props extends Record<string, any>,
  ...,
  DeclaredProps extends (keyof Props)[] = (keyof Props)[],
>(
  setup: (props: Props, ...) => ...,
  options?: Pick<ComponentOptions, 'name' | 'inheritAttrs'> & {
    props?: DeclaredProps
    ...
  },
): DefineSetupFnComponent<Props, E, S>

A note about an object format for props with runtime validations

This MR fixes only the usage with props defined as an array of strings. I haven't found any solution for the object format and I'm not sure that there is one...

But on the other side, I don't think someone would need to combine generics with runtime validations

Summary by CodeRabbit

  • Tests

    • Expanded and refined test coverage for component definitions with runtime props, including scenarios with generics and TypeScript error expectations.
    • Added JSX usage tests to verify correct and incorrect prop usage, type checking, and readonly behavior.
  • New Features

    • Improved type inference and customization for runtime props in component definitions, enhancing TypeScript support for advanced use cases.

@jh-leong

This comment was marked as outdated.

Copy link
github-actions bot commented Mar 31, 2025
8000

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB (-182 B) 38.2 kB (-64 B) 34.4 kB (-41 B)
vue.global.prod.js 159 kB (-182 B) 58.4 kB (-66 B) 52 kB (-22 B)

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.6 kB (-1 B) 18.2 kB (-1 B) 16.7 kB
createApp 54.5 kB (-7 B) 21.2 kB (-7 B) 19.4 kB (+2 B)
createSSRApp 58.7 kB (-7 B) 23 kB (-8 B) 20.9 kB (-6 B)
defineCustomElement 59.3 kB (-145 B) 22.8 kB (-42 B) 20.8 kB (-39 B)
overall 68.6 kB (-7 B) 26.4 kB (-6 B) 24 kB (-76 B)

Copy link
pkg-pr-new bot commented Mar 31, 2025

Open in StackBlitz

@vue/compiler-core

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

@vue/compiler-dom

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

@vue/compiler-sfc

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

@vue/compiler-ssr

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

@vue/reactivity

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

@vue/runtime-core

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

@vue/runtime-dom

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

@vue/server-renderer

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

@vue/shared

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

vue

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

@vue/compat

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

commit: 5e1f00a

@jh-leong
Copy link
Member

/ecosystem-ci run

@vue-bot
Copy link
Contributor
vue-bot commented Mar 31, 2025

📝 Ran ecosystem CI: Open

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

@danyadev danyadev force-pushed the fix-generic-defineComponent-with-runtime-props branch from cf9276c to d7d0e0e Compare May 15, 2025 20:28
Copy link
coderabbitai bot commented May 15, 2025

Walkthrough

The changes enhance the typing system for the defineComponent API by modifying the props parameter type to use NoInfer<Props> and expand the test suite with comprehensive cases covering function-based components, runtime props declarations (array and object), generics, and TypeScript JSX usage, including explicit error expectations for mismatches and unsupported scenarios.

Changes

File(s) Change Summary
packages/runtime-core/src/apiDefineComponent.ts Changed the props parameter type in the first overload of defineComponent from (keyof Props)[] to (keyof NoInfer<Props>)[].
packages-private/dts-test/defineComponent.test-d.tsx Added extensive tests for defineComponent with function syntax, runtime props (array and object), generics, and JSX usage with expected TS errors.

Sequence Diagram(s)

sequenceDiagram
    participant TSXUser as TSX User
    participant CompDef as defineComponent
    participant TypeScript as TypeScript Checker

    TSXUser->>CompDef: Define component with generics and runtime props
    CompDef->>TypeScript: Infer prop types and generics
    TypeScript-->>CompDef: Validate types and report errors
    TSXUser->>CompDef: Use component in JSX with props and generics
    CompDef->>TypeScript: Type-check prop usage
    TypeScript-->>TSXUser: Report correctness or errors
Loading

Assessment against linked issues

Objective Addressed Explanation
Support generics in TSX component definitions and usage (#11374)
Correct type inference and error reporting for runtime props and generics in defineComponent (#11374)
TypeScript error handling for incorrect prop usage and unsupported generics in object runtime props (#11374)

Poem

A rabbit hops through fields of types,
Where generics bloom and TSX delights.
Props checked with care, errors in sight,
Now components flex with runtime might.
With every test, the meadow grows—
Type-safe carrots, in tidy rows!
🥕✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between d7d0e0e and 5e1f00a.

📒 Files selected for processing (2)
  • packages-private/dts-test/defineComponent.test-d.tsx (4 hunks)
  • packages/runtime-core/src/apiDefineComponent.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/runtime-core/src/apiDefineComponent.ts
  • packages-private/dts-test/defineComponent.test-d.tsx
✨ 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.
    • 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.

@danyadev danyadev changed the title fix: make generics with runtime props in defineComponent work (fix #11374) fix(types): make generics with runtime props in defineComponent work (fix #11374) May 15, 2025
@danyadev danyadev force-pushed the fix-generic-defineComponent-with-runtime-props branch from d7d0e0e to 5e1f00a Compare May 15, 2025 20:38
@danyadev
Copy link
Author
danyadev commented May 15, 2025

Hi @jh-leong! Rebased the MR on the main branch to pick up all the changes from the released version, but it seems that the pkg-pr-new bot doesn't want to update its builds, and maybe you know how to bump it?

upd: it updated the builds, it seems like the pipelines were a bit clogged at the time and didn't show that they were in progress

Also updated the description and hopefully made it fresher and easier to understand, plus added the link to the playground!

Really need this feature, so I've been using it right from the creation of this MR :)

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.

How to use generics in TSX
4 participants
0