fix(types/sfc): fix withDefaults type inference when using union types (#4925)

This commit is contained in:
Cathrine Vaage 2021-11-15 04:09:00 +01:00 committed by GitHub
parent fa2237f1d8
commit 04e5835196
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 12 deletions

View File

@ -127,18 +127,19 @@ export function defineExpose(exposed?: Record<string, any>) {
type NotUndefined<T> = T extends undefined ? never : T type NotUndefined<T> = T extends undefined ? never : T
type InferDefaults<T> = { type InferDefaults<T> = {
[K in keyof T]?: NotUndefined<T[K]> extends [K in keyof T]?: InferDefault<T, NotUndefined<T[K]>>
}
type InferDefault<P, T> = T extends
| number | number
| string | string
| boolean | boolean
| symbol | symbol
| Function | Function
? NotUndefined<T[K]> ? T
: (props: T) => NotUndefined<T[K]> : (props: P) => T
}
type PropsWithDefaults<Base, Defaults> = Base & type PropsWithDefaults<Base, Defaults> = Base & {
{
[K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never [K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
} }

View File

@ -45,6 +45,21 @@ describe('defineProps w/ type declaration + withDefaults', () => {
res.x.slice() 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', () => { describe('defineProps w/ runtime declaration', () => {
// runtime declaration // runtime declaration
const props = defineProps({ const props = defineProps({