]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(types/sfc): fix withDefaults type inference when using union types (#4925)
authorCathrine Vaage <cathrine.vaage@gmail.com>
Mon, 15 Nov 2021 03:09:00 +0000 (04:09 +0100)
committerGitHub <noreply@github.com>
Mon, 15 Nov 2021 03:09:00 +0000 (22:09 -0500)
packages/runtime-core/src/apiSetupHelpers.ts
test-dts/setupHelpers.test-d.ts

index 292b2f42f7afad6d3cf8e8c885baff7141232cee..fc1866af958b210ec739f1a995d3bd5ce9751e54 100644 (file)
@@ -127,20 +127,21 @@ export function defineExpose(exposed?: Record<string, any>) {
 type NotUndefined<T> = T extends undefined ? never : T
 
 type InferDefaults<T> = {
-  [K in keyof T]?: NotUndefined<T[K]> extends
-    | number
-    | string
-    | boolean
-    | symbol
-    | Function
-    ? NotUndefined<T[K]>
-    : (props: T) => NotUndefined<T[K]>
+  [K in keyof T]?: InferDefault<T, NotUndefined<T[K]>>
 }
 
-type PropsWithDefaults<Base, Defaults> = Base &
-  {
-    [K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
-  }
+type InferDefault<P, T> = T extends
+  | number
+  | string
+  | boolean
+  | symbol
+  | Function
+  ? T
+  : (props: P) => T
+
+type PropsWithDefaults<Base, Defaults> = Base & {
+  [K in keyof Defaults]: K extends keyof Base ? NotUndefined<Base[K]> : never
+}
 
 /**
  * Vue `<script setup>` compiler macro for providing props default values when
index 1b4a2ff43ad294b63b4932c5f875092e5b4aab9c..155ba337dcfa0a7c1f0267c3aa37c2ca089c7e7d 100644 (file)
@@ -45,6 +45,21 @@ describe('defineProps w/ type declaration + withDefaults', () => {
   res.x.slice()
 })
 
+describe('defineProps w/ union type declaration + withDefaults', () => {
+  withDefaults(
+    defineProps<{
+      union1?: number | number[] | { x: number }
+      union2?: number | number[] | { x: number }
+      union3?: number | number[] | { x: number }
+    }>(),
+    {
+      union1: 123,
+      union2: () => [123],
+      union3: () => ({ x: 123 })
+    }
+  )
+})
+
 describe('defineProps w/ runtime declaration', () => {
   // runtime declaration
   const props = defineProps({