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

fix #6552
This commit is contained in:
littleboarx 2022-11-08 10:59:31 +08:00 committed by GitHub
parent 79e7c1ee43
commit 168c857247
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 4 deletions

View File

@ -143,7 +143,11 @@ type InferDefault<P, T> = T extends
: (props: P) => T
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
}
/**

View File

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