Skip to content

Commit

Permalink
fix(types/sfc): improve the type inference using withDefaults (#12872)
Browse files Browse the repository at this point in the history
  • Loading branch information
webfansplz authored Oct 23, 2023
1 parent 67c1d26 commit 099401e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
16 changes: 13 additions & 3 deletions types/test/setup-helpers-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,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
6 changes: 5 additions & 1 deletion types/v3-setup-helpers.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,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

0 comments on commit 099401e

Please sign in to comment.