Skip to content

fix(types): retain union type narrowing with defaults applied #12108

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

Merged
merged 2 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages-private/dts-test/setupHelpers.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ describe('defineProps w/ type declaration + withDefaults', <T extends
bool?: boolean
boolAndUndefined: boolean | undefined
foo?: T
u:
| { type: 'button'; buttonType?: 'submit' }
| { type: 'link'; href: string }
}>(),
{
number: 123,
Expand Down Expand Up @@ -88,6 +91,13 @@ describe('defineProps w/ type declaration + withDefaults', <T extends

expectType<boolean>(res.bool)
expectType<boolean>(res.boolAndUndefined)

if (res.u.type === 'button') {
expectType<'submit' | undefined>(res.u.buttonType)
}
if (res.u.type === 'link') {
expectType<string>(res.u.href)
}
})

describe('defineProps w/ union type declaration + withDefaults', () => {
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