Skip to content

Commit 495263a

Browse files
authoredJun 14, 2024··
fix(compiler-sfc): support type resolve for keyof for intersection & union types (#11132)
close #11129
1 parent b557d3f commit 495263a

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed
 

‎packages/compiler-sfc/__tests__/compileScript/resolveType.spec.ts

+25
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,31 @@ describe('resolveType', () => {
513513
})
514514
})
515515

516+
// #11129
517+
test('keyof: intersection type', () => {
518+
const { props } = resolve(`
519+
type A = { name: string }
520+
type B = A & { [key: number]: string }
521+
defineProps<{
522+
foo: keyof B
523+
}>()`)
524+
expect(props).toStrictEqual({
525+
foo: ['String', 'Number'],
526+
})
527+
})
528+
529+
test('keyof: union type', () => {
530+
const { props } = resolve(`
531+
type A = { name: string }
532+
type B = A | { [key: number]: string }
533+
defineProps<{
534+
foo: keyof B
535+
}>()`)
536+
expect(props).toStrictEqual({
537+
foo: ['String', 'Number'],
538+
})
539+
})
540+
516541
test('keyof: utility type', () => {
517542
const { props } = resolve(
518543
`

‎packages/compiler-sfc/src/script/resolveType.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -1686,9 +1686,9 @@ export function inferRuntimeType(
16861686
return inferRuntimeType(ctx, node.typeAnnotation, scope)
16871687

16881688
case 'TSUnionType':
1689-
return flattenTypes(ctx, node.types, scope)
1689+
return flattenTypes(ctx, node.types, scope, isKeyOf)
16901690
case 'TSIntersectionType': {
1691-
return flattenTypes(ctx, node.types, scope).filter(
1691+
return flattenTypes(ctx, node.types, scope, isKeyOf).filter(
16921692
t => t !== UNKNOWN_TYPE,
16931693
)
16941694
}
@@ -1760,14 +1760,15 @@ function flattenTypes(
17601760
ctx: TypeResolveContext,
17611761
types: TSType[],
17621762
scope: TypeScope,
1763+
isKeyOf: boolean = false,
17631764
): string[] {
17641765
if (types.length === 1) {
1765-
return inferRuntimeType(ctx, types[0], scope)
1766+
return inferRuntimeType(ctx, types[0], scope, isKeyOf)
17661767
}
17671768
return [
17681769
...new Set(
17691770
([] as string[]).concat(
1770-
...types.map(t => inferRuntimeType(ctx, t, scope)),
1771+
...types.map(t => inferRuntimeType(ctx, t, scope, isKeyOf)),
17711772
),
17721773
),
17731774
]

0 commit comments

Comments
 (0)
Please sign in to comment.