]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(compiler-sfc): support type resolve for keyof for intersection & union types...
authorZhaolin Liang <develop0304@outlook.com>
Fri, 14 Jun 2024 09:10:46 +0000 (17:10 +0800)
committerGitHub <noreply@github.com>
Fri, 14 Jun 2024 09:10:46 +0000 (17:10 +0800)
close #11129

packages/compiler-sfc/__tests__/compileScript/resolveType.spec.ts
packages/compiler-sfc/src/script/resolveType.ts

index 93bd20879ae94151aedf34c9e938ccfd5903b4d4..608549de6f3902ab70e7962943f4c3268a5c8607 100644 (file)
@@ -513,6 +513,31 @@ describe('resolveType', () => {
     })
   })
 
+  // #11129
+  test('keyof: intersection type', () => {
+    const { props } = resolve(`
+    type A = { name: string }
+    type B = A & { [key: number]: string }
+    defineProps<{
+      foo: keyof B
+    }>()`)
+    expect(props).toStrictEqual({
+      foo: ['String', 'Number'],
+    })
+  })
+
+  test('keyof: union type', () => {
+    const { props } = resolve(`
+    type A = { name: string }
+    type B = A | { [key: number]: string }
+    defineProps<{
+      foo: keyof B
+    }>()`)
+    expect(props).toStrictEqual({
+      foo: ['String', 'Number'],
+    })
+  })
+
   test('keyof: utility type', () => {
     const { props } = resolve(
       `
index de44b9a5e7e99ebd672b3d02775740272969b2b9..c1204a4cd238a3503ee3d12cc3e688a61d68422f 100644 (file)
@@ -1686,9 +1686,9 @@ export function inferRuntimeType(
         return inferRuntimeType(ctx, node.typeAnnotation, scope)
 
       case 'TSUnionType':
-        return flattenTypes(ctx, node.types, scope)
+        return flattenTypes(ctx, node.types, scope, isKeyOf)
       case 'TSIntersectionType': {
-        return flattenTypes(ctx, node.types, scope).filter(
+        return flattenTypes(ctx, node.types, scope, isKeyOf).filter(
           t => t !== UNKNOWN_TYPE,
         )
       }
@@ -1760,14 +1760,15 @@ function flattenTypes(
   ctx: TypeResolveContext,
   types: TSType[],
   scope: TypeScope,
+  isKeyOf: boolean = false,
 ): string[] {
   if (types.length === 1) {
-    return inferRuntimeType(ctx, types[0], scope)
+    return inferRuntimeType(ctx, types[0], scope, isKeyOf)
   }
   return [
     ...new Set(
       ([] as string[]).concat(
-        ...types.map(t => inferRuntimeType(ctx, t, scope)),
+        ...types.map(t => inferRuntimeType(ctx, t, scope, isKeyOf)),
       ),
     ),
   ]