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 2 commits 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

Summary by CodeRabbit

  • Tests

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

    • Enhanced type inference for component runtime props with a new function overload using a utility type to prevent premature generic type inference.

Copy link

github-actions bot commented Mar 31, 2025

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

@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 Added new overload of defineComponent with props typed as (keyof NoInfer<Props>)[] to prevent eager inference of generics.
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)

Suggested reviewers

  • johnsoncodehk
  • edison1105

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!
🥕✨


📜 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 5e1f00a and b8cc94b.

📒 Files selected for processing (2)
  • packages-private/dts-test/defineComponent.test-d.tsx (5 hunks)
  • packages/runtime-core/src/apiDefineComponent.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/runtime-core/src/apiDefineComponent.ts

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

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

(lint/complexity/noBannedTypes)


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

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

(lint/complexity/noBannedTypes)

🔇 Additional comments (3)
packages/runtime-core/src/apiDefineComponent.ts (1)

165-180: LGTM! The new overload correctly addresses the generic type inference issue.

The addition of NoInfer<Props> on line 176 prevents TypeScript from inferring the Props generic from the runtime props array, ensuring that generics are properly inferred from the setup function parameter instead. This is a well-targeted fix for the issue described in #11374.

🧰 Tools
🪛 Biome (1.9.4)

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

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

(lint/complexity/noBannedTypes)


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

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

(lint/complexity/noBannedTypes)

packages-private/dts-test/defineComponent.test-d.tsx (2)

5-5: Import addition looks good.

The DefineSetupFnComponent type import is appropriately added to support the new test cases.


1403-1562: Excellent test coverage for the new defineComponent overload!

The test suite comprehensively validates:

  • ✅ Basic runtime props array functionality (Comp1)
  • ✅ Generic type inference preservation with runtime props arrays (Comp2)
  • ✅ Error detection for prop mismatches between runtime and type declarations
  • ✅ Compromise behavior when runtime props exceed manual types (Comp3)
  • ✅ Lack of generic support with object-style runtime props (Comp4)
  • ✅ Proper type inference without explicit props types (Comp5)

The tests effectively demonstrate both the capabilities and limitations of the fix, aligning perfectly with the PR objectives.

✨ 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.

@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 :)

@@ -157,7 +157,7 @@ export function defineComponent<
ctx: SetupContext<E, S>,
) => RenderFunction | Promise<RenderFunction>,
options?: Pick<ComponentOptions, 'name' | 'inheritAttrs'> & {
props?: (keyof Props)[]
props?: (keyof NoInfer<Props>)[]
Copy link
Member

Choose a reason for hiding this comment

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

One concern, to avoid breaking this case:

defineComponent(
  props => {
    // Before: { msg: any }
    // After : Record<string, any>

    // @ts-expect-error: should error when accessing undefined props
    props.foo

    // auto-completion missing for props
    props.msg

    return () => {}
  },
  {
    props: ['msg']
  }
)

We might want to keep the original behavior by adding a new overload instead:

// overload 1: direct setup function
// (uses user defined props interface)
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>
+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 NoInfer<Props>)[]
+    emits?: E | EE[]
+    slots?: S
+  },
+)

Copy link
Author

Choose a reason for hiding this comment

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

I see, but the proposed solution breaks another thing: if runtime props contain more props than declared in props, and the function is generic, the types fall back to any:

image image

(@ts-expect-error is red because there was an error, but it's gone now)

It's still the best solution though, I've tried some variants and none of them worked

Copy link
Author

Choose a reason for hiding this comment

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

applied your solution for now and added a few tests

Copy link
Member

Choose a reason for hiding this comment

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

I believe this issue is negligible in practice — it only happens when props is both generic and doesn't match the runtime props, which seems rare.

@jh-leong jh-leong added the 🍰 p2-nice-to-have Priority 2: this is not breaking anything but nice to have it addressed. label Jun 10, 2025
@danyadev danyadev force-pushed the fix-generic-defineComponent-with-runtime-props branch from 5e1f00a to b8cc94b Compare June 11, 2025 17:28
@vuejs vuejs deleted a comment from jh-leong Jun 12, 2025
@vuejs vuejs deleted a comment from jh-leong Jun 12, 2025
@jh-leong
Copy link
Member

/ecosystem-ci run

@vue-bot
Copy link
Contributor

vue-bot commented Jun 12, 2025

📝 Ran ecosystem CI: Open

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

@vuejs vuejs deleted a comment from jh-leong Jun 12, 2025
@jh-leong jh-leong self-requested a review June 12, 2025 06:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🍰 p2-nice-to-have Priority 2: this is not breaking anything but nice to have it addressed. scope: types
Projects
None yet
Development

Successfully merging this pull request may close these issues.

How to use generics in TSX
4 participants