mirror of https://github.com/vuejs/core.git
fix(sfc/types): improve the type inference using withDefaults (#6764)
fix #6552
This commit is contained in:
parent
79e7c1ee43
commit
168c857247
|
@ -143,7 +143,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
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -27,15 +27,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'
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -43,9 +47,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', () => {
|
||||||
|
|
Loading…
Reference in New Issue