Skip to content
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

fix(types): Use alternative Omit that enables discriminated unions in props #9336

Merged
merged 4 commits into from
Aug 2, 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
25 changes: 25 additions & 0 deletions packages/dts-test/setupHelpers.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,31 @@ describe('defineProps w/ union type declaration + withDefaults', () => {
)
})

describe('defineProps w/ generic discriminate union + withDefaults', () => {
interface B {
b?: string
}
interface S<T> extends B {
mode: 'single'
v: T
}
interface M<T> extends B {
mode: 'multiple'
v: T[]
}
type Props = S<string> | M<string>
const props = withDefaults(defineProps<Props>(), {
b: 'b'
})

if (props.mode === 'single') {
expectType<string>(props.v)
}
if (props.mode === 'multiple') {
expectType<string[]>(props.v)
}
})

describe('defineProps w/ generic type declaration + withDefaults', <T extends
number, TA extends {
a: string
Expand Down
7 changes: 6 additions & 1 deletion packages/runtime-core/src/apiSetupHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -293,11 +293,16 @@ type InferDefault<P, T> =
| ((props: P) => T & {})
| (T extends NativeType ? T : never)

// https://github.com/vuejs/core/issues/9335
type OmitKeepDiscriminatedUnion<T, K extends keyof any> = T extends any
? Pick<T, Exclude<keyof T, K>>
: never

type PropsWithDefaults<
T,
Defaults extends InferDefaults<T>,
BKeys extends keyof T
> = Omit<T, keyof Defaults> & {
> = OmitKeepDiscriminatedUnion<T, keyof Defaults> & {
[K in keyof Defaults]-?: K extends keyof T
? Defaults[K] extends undefined
? T[K]
Expand Down