fix(types/sfc): improve the type inference using withDefaults (#12872)

This commit is contained in:
webfansplz 2023-10-23 15:06:28 +08:00 committed by GitHub
parent 67c1d26cb0
commit 099401e227
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 4 deletions

View File

@ -19,15 +19,19 @@ describe('defineProps w/ type declaration + withDefaults', () => {
arr?: string[] arr?: string[]
obj?: { x: number } obj?: { x: number }
fn?: (e: string) => void fn?: (e: string) => void
x?: string
genStr?: string genStr?: string
x?: string
y?: string
z?: string
}>(), }>(),
{ {
number: 123, number: 123,
arr: () => [], arr: () => [],
obj: () => ({ x: 123 }), obj: () => ({ x: 123 }),
fn: () => {}, fn: () => {},
genStr: () => '' genStr: () => '',
y: undefined,
z: 'string'
} }
) )
@ -35,9 +39,15 @@ describe('defineProps w/ type declaration + withDefaults', () => {
res.arr.push('hi') res.arr.push('hi')
res.obj.x res.obj.x
res.fn('hi') res.fn('hi')
res.genStr.slice()
// @ts-expect-error // @ts-expect-error
res.x.slice() res.x.slice()
res.genStr.slice() // @ts-expect-error
res.y.slice()
expectType<string | undefined>(res.x)
expectType<string | undefined>(res.y)
expectType<string>(res.z)
}) })
describe('defineProps w/ union type declaration + withDefaults', () => { describe('defineProps w/ union type declaration + withDefaults', () => {

View File

@ -110,7 +110,11 @@ type InferDefault<P, T> = T extends
: (props: P) => T : (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
? Defaults[K] extends undefined
? Base[K]
: NotUndefined<Base[K]>
: never
} }
/** /**