Skip to content

Commit

Permalink
fix(sfc/types): improve the type inference using withDefaults (#6764)
Browse files Browse the repository at this point in the history
fix #6552
  • Loading branch information
littleboarx committed Nov 8, 2022
1 parent 79e7c1e commit 168c857
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
6 changes: 5 additions & 1 deletion packages/runtime-core/src/apiSetupHelpers.ts
Expand Up @@ -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
}

/**
Expand Down
16 changes: 13 additions & 3 deletions test-dts/setupHelpers.test-d.ts
Expand Up @@ -27,25 +27,35 @@ 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'
}
)

res.number + 1
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', () => {
Expand Down

0 comments on commit 168c857

Please sign in to comment.