Skip to content

Commit

Permalink
fix(compiler-sfc): support type resolve for keyof for intersection & …
Browse files Browse the repository at this point in the history
…union types (#11132)

close #11129
  • Loading branch information
lzl0304 committed Jun 14, 2024
1 parent b557d3f commit 495263a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
25 changes: 25 additions & 0 deletions packages/compiler-sfc/__tests__/compileScript/resolveType.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
`
Expand Down
9 changes: 5 additions & 4 deletions packages/compiler-sfc/src/script/resolveType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
}
Expand Down Expand Up @@ -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)),
),
),
]
Expand Down

0 comments on commit 495263a

Please sign in to comment.