Parcourir la source

fix(sfc/types): allow use default factory for primitive types in `withDefaults` (#5939)

fix #5938
Alex Kozack il y a 3 ans
Parent
commit
b5462822d6

+ 1 - 1
packages/runtime-core/src/apiSetupHelpers.ts

@@ -139,7 +139,7 @@ type InferDefault<P, T> = T extends
   | boolean
   | symbol
   | Function
-  ? T
+  ? T | ((props: P) => T)
   : (props: P) => T
 
 type PropsWithDefaults<Base, Defaults> = Base & {

+ 7 - 2
test-dts/setupHelpers.test-d.ts

@@ -28,12 +28,14 @@ describe('defineProps w/ type declaration + withDefaults', () => {
       obj?: { x: number }
       fn?: (e: string) => void
       x?: string
+      genStr?: string
     }>(),
     {
       number: 123,
       arr: () => [],
       obj: () => ({ x: 123 }),
-      fn: () => {}
+      fn: () => {},
+      genStr: () => ''
     }
   )
 
@@ -43,6 +45,7 @@ describe('defineProps w/ type declaration + withDefaults', () => {
   res.fn('hi')
   // @ts-expect-error
   res.x.slice()
+  res.genStr.slice()
 })
 
 describe('defineProps w/ union type declaration + withDefaults', () => {
@@ -51,11 +54,13 @@ describe('defineProps w/ union type declaration + withDefaults', () => {
       union1?: number | number[] | { x: number }
       union2?: number | number[] | { x: number }
       union3?: number | number[] | { x: number }
+      union4?: number | number[] | { x: number }
     }>(),
     {
       union1: 123,
       union2: () => [123],
-      union3: () => ({ x: 123 })
+      union3: () => ({ x: 123 }),
+      union4: () => 123,
     }
   )
 })