Skip to content

Commit

Permalink
fix(types): retain union type narrowing with defaults applied (#12108)
Browse files Browse the repository at this point in the history
close #12106
  • Loading branch information
edison1105 authored and yyx990803 committed Oct 11, 2024
1 parent cde2c06 commit 05685a9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 15 deletions.
17 changes: 17 additions & 0 deletions packages-private/dts-test/setupHelpers.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,23 @@ describe('withDefaults w/ defineProp type is different from the defaults type',
res1.value
})

describe('withDefaults w/ defineProp discriminate union type', () => {
const props = withDefaults(
defineProps<
{ type: 'button'; buttonType?: 'submit' } | { type: 'link'; href: string }
>(),
{
type: 'button',
},
)
if (props.type === 'button') {
expectType<'submit' | undefined>(props.buttonType)
}
if (props.type === 'link') {
expectType<string>(props.href)
}
})

describe('defineProps w/ runtime declaration', () => {
// runtime declaration
const props = defineProps({
Expand Down
32 changes: 17 additions & 15 deletions packages/runtime-core/src/apiSetupHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,21 +331,23 @@ type PropsWithDefaults<
T,
Defaults extends InferDefaults<T>,
BKeys extends keyof T,
> = Readonly<MappedOmit<T, keyof Defaults>> & {
readonly [K in keyof Defaults as K extends keyof T
? K
: never]-?: K extends keyof T
? Defaults[K] extends undefined
? IfAny<Defaults[K], NotUndefined<T[K]>, T[K]>
: NotUndefined<T[K]>
: never
} & {
readonly [K in BKeys]-?: K extends keyof Defaults
? Defaults[K] extends undefined
? boolean | undefined
: boolean
: boolean
}
> = T extends unknown
? Readonly<MappedOmit<T, keyof Defaults>> & {
readonly [K in keyof Defaults as K extends keyof T
? K
: never]-?: K extends keyof T
? Defaults[K] extends undefined
? IfAny<Defaults[K], NotUndefined<T[K]>, T[K]>
: NotUndefined<T[K]>
: never
} & {
readonly [K in BKeys]-?: K extends keyof Defaults
? Defaults[K] extends undefined
? boolean | undefined
: boolean
: boolean
}
: never

/**
* Vue `<script setup>` compiler macro for providing props default values when
Expand Down

0 comments on commit 05685a9

Please sign in to comment.