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(runtime-core): add InferDefaults handling of array and object union types #4925

Merged
merged 2 commits into from Nov 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 13 additions & 12 deletions packages/runtime-core/src/apiSetupHelpers.ts
Expand Up @@ -127,20 +127,21 @@ export function defineExpose(exposed?: Record<string, any>) {
type NotUndefined<T> = T extends undefined ? never : T

type InferDefaults<T> = {
[K in keyof T]?: NotUndefined<T[K]> extends
| number
| string
| boolean
| symbol
| Function
? NotUndefined<T[K]>
: (props: T) => NotUndefined<T[K]>
[K in keyof T]?: InferDefault<T, NotUndefined<T[K]>>
}

type PropsWithDefaults<Base, Defaults> = Base &
{
[K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
}
type InferDefault<P, T> = T extends
Copy link
Member

Choose a reason for hiding this comment

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

The original logic seemed unnecessarily complex so I refactored it - thanks for the fix and the test case though!

| number
| string
| boolean
| symbol
| Function
? T
: (props: P) => T

type PropsWithDefaults<Base, Defaults> = Base & {
[K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
}

/**
* Vue `<script setup>` compiler macro for providing props default values when
Expand Down
15 changes: 15 additions & 0 deletions test-dts/setupHelpers.test-d.ts
Expand Up @@ -45,6 +45,21 @@ describe('defineProps w/ type declaration + withDefaults', () => {
res.x.slice()
})

describe('defineProps w/ union type declaration + withDefaults', () => {
withDefaults(
defineProps<{
union1?: number | number[] | { x: number }
union2?: number | number[] | { x: number }
union3?: number | number[] | { x: number }
}>(),
{
union1: 123,
union2: () => [123],
union3: () => ({ x: 123 })
}
)
})

describe('defineProps w/ runtime declaration', () => {
// runtime declaration
const props = defineProps({
Expand Down