Przeglądaj źródła

feat(compiler-sfc): improve utility type Partial and Required (#8103)

edison 3 lat temu
rodzic
commit
1d1d728949

+ 32 - 0
packages/compiler-sfc/__tests__/compileScript/resolveType.spec.ts

@@ -207,6 +207,38 @@ describe('resolveType', () => {
     })
   })
 
+  test('utility type: Partial', () => {
+    expect(
+      resolve(`
+    type T = { foo: number, bar: string }
+    defineProps<Partial<T>>()
+    `).raw.props
+    ).toMatchObject({
+      foo: {
+        optional: true
+      },
+      bar: {
+        optional: true
+      }
+    })
+  })
+
+  test('utility type: Required', () => {
+    expect(
+      resolve(`
+    type T = { foo?: number, bar?: string }
+    defineProps<Required<T>>()
+    `).raw.props
+    ).toMatchObject({
+      foo: {
+        optional: false
+      },
+      bar: {
+        optional: false
+      }
+    })
+  })
+
   test('utility type: Pick', () => {
     expect(
       resolve(`

+ 14 - 2
packages/compiler-sfc/src/script/resolveType.ts

@@ -513,8 +513,20 @@ function resolveBuiltin(
 ): ResolvedElements {
   const t = resolveTypeElements(ctx, node.typeParameters!.params[0])
   switch (name) {
-    case 'Partial':
-    case 'Required':
+    case 'Partial': {
+      const res: ResolvedElements = { props: {}, calls: t.calls }
+      Object.keys(t.props).forEach(key => {
+        res.props[key] = { ...t.props[key], optional: true }
+      })
+      return res
+    }
+    case 'Required': {
+      const res: ResolvedElements = { props: {}, calls: t.calls }
+      Object.keys(t.props).forEach(key => {
+        res.props[key] = { ...t.props[key], optional: false }
+      })
+      return res
+    }
     case 'Readonly':
       return t
     case 'Pick': {