From 5179d328d950015e7fb2a74fe1a8518fd8d2c94e Mon Sep 17 00:00:00 2001 From: Tycho Date: Thu, 22 May 2025 08:03:33 +0800 Subject: [PATCH] fix(types): exclude `undefined` from inferred prop types with default values (#13007) close #13006 --- .../dts-test/defineComponent.test-d.tsx | 29 +++++++++++++++++++ packages/runtime-core/src/componentProps.ts | 4 ++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/packages-private/dts-test/defineComponent.test-d.tsx b/packages-private/dts-test/defineComponent.test-d.tsx index fda3ca485..1967668dc 100644 --- a/packages-private/dts-test/defineComponent.test-d.tsx +++ b/packages-private/dts-test/defineComponent.test-d.tsx @@ -20,6 +20,9 @@ import { type IsAny, type IsUnion, describe, expectType } from './utils' describe('with object props', () => { interface ExpectedProps { a?: number | undefined + aa: number + aaa: number | null + aaaa: number | undefined b: string e?: Function h: boolean @@ -53,6 +56,19 @@ describe('with object props', () => { const props = { a: Number, + aa: { + type: Number as PropType, + default: 1, + }, + aaa: { + type: Number as PropType, + default: 1, + }, + aaaa: { + type: Number as PropType, + // `as const` prevents widening to `boolean` (keeps literal `true` type) + required: true as const, + }, // required should make property non-void b: { type: String, @@ -146,6 +162,13 @@ describe('with object props', () => { setup(props) { // type assertion. See https://github.com/SamVerschueren/tsd expectType(props.a) + expectType(props.aa) + expectType(props.aaa) + + // @ts-expect-error should included `undefined` + expectType(props.aaaa) + expectType(props.aaaa) + expectType(props.b) expectType(props.e) expectType(props.h) @@ -198,6 +221,8 @@ describe('with object props', () => { render() { const props = this.$props expectType(props.a) + expectType(props.aa) + expectType(props.aaa) expectType(props.b) expectType(props.e) expectType(props.h) @@ -225,6 +250,8 @@ describe('with object props', () => { // should also expose declared props on `this` expectType(this.a) + expectType(this.aa) + expectType(this.aaa) expectType(this.b) expectType(this.e) expectType(this.h) @@ -269,6 +296,7 @@ describe('with object props', () => { expectType( {}} @@ -295,6 +323,7 @@ describe('with object props', () => { expectType( = [T] extends [null] export type ExtractPropTypes = { // use `keyof Pick>` instead of `RequiredKeys` to // support IDE features - [K in keyof Pick>]: InferPropType + [K in keyof Pick>]: O[K] extends { default: any } + ? Exclude, undefined> + : InferPropType } & { // use `keyof Pick>` instead of `OptionalKeys` to // support IDE features