Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(compiler-sfc): support keyof for intersection types #11132

Merged
merged 3 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 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,19 @@ describe('resolveType', () => {
})
})

// #11129
test('keyof: intersection type', () => {
const { props } = resolve(`
type A = { name: string }
type B = A & { color: string }
defineProps<{
foo: keyof B
}>()`)
expect(props).toStrictEqual({
foo: ['String'],
})
})

test('keyof: utility type', () => {
const { props } = resolve(
`
Expand Down
7 changes: 4 additions & 3 deletions packages/compiler-sfc/src/script/resolveType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1688,7 +1688,7 @@ export function inferRuntimeType(
case 'TSUnionType':
return flattenTypes(ctx, node.types, scope)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this also apply to UnionTypes?

Copy link
Contributor Author

@lzl0304 lzl0304 Jun 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I've also encountered an issue with union types during testing(keyof A):

  • When type A = 'a' | 'b', resolveType correctly returns ['String'].
  • When type A = number | string, resolveType returns ['Number', 'String'], but in TypeScript, the type of A should be "toString" | "valueOf".

Given this, I believe this might be another issue, and simply adding a parameter might not fix it. Do you think fixing this issue is necessary? If necessary, I'll try to address it.

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