fix(compiler-sfc): avoid all hard errors when inferring runtime type

This commit is contained in:
Evan You 2023-04-21 16:48:21 +08:00
parent 1447596bf4
commit 2d9f6f9264
2 changed files with 165 additions and 149 deletions

View File

@ -690,6 +690,12 @@ describe('resolveType', () => {
test('should not error on unresolved type when inferring runtime type', () => {
expect(() => resolve(`defineProps<{ foo: T }>()`)).not.toThrow()
expect(() => resolve(`defineProps<{ foo: T['bar'] }>()`)).not.toThrow()
expect(() =>
resolve(`
import type P from 'unknown'
defineProps<{ foo: P }>()
`)
).not.toThrow()
})
})
})

View File

@ -1180,6 +1180,7 @@ export function inferRuntimeType(
node: Node & MaybeWithScope,
scope = node._ownerScope || ctxToScope(ctx)
): string[] {
try {
switch (node.type) {
case 'TSStringKeyword':
return ['String']
@ -1211,7 +1212,11 @@ export function inferRuntimeType(
}
case 'TSPropertySignature':
if (node.typeAnnotation) {
return inferRuntimeType(ctx, node.typeAnnotation.typeAnnotation, scope)
return inferRuntimeType(
ctx,
node.typeAnnotation.typeAnnotation,
scope
)
}
case 'TSMethodSignature':
case 'TSFunctionType':
@ -1284,13 +1289,21 @@ export function inferRuntimeType(
break
case 'Extract':
if (node.typeParameters && node.typeParameters.params[1]) {
return inferRuntimeType(ctx, node.typeParameters.params[1], scope)
return inferRuntimeType(
ctx,
node.typeParameters.params[1],
scope
)
}
break
case 'Exclude':
case 'OmitThisParameter':
if (node.typeParameters && node.typeParameters.params[0]) {
return inferRuntimeType(ctx, node.typeParameters.params[0], scope)
return inferRuntimeType(
ctx,
node.typeParameters.params[0],
scope
)
}
break
}
@ -1317,19 +1330,14 @@ export function inferRuntimeType(
return ['Symbol']
case 'TSIndexedAccessType': {
try {
const types = resolveIndexType(ctx, node, scope)
return flattenTypes(ctx, types, scope)
} catch (e) {
break
}
}
case 'ClassDeclaration':
return ['Object']
case 'TSImportType': {
try {
const sourceScope = importSourceToScope(
ctx,
node.argument,
@ -1340,7 +1348,6 @@ export function inferRuntimeType(
if (resolved) {
return inferRuntimeType(ctx, resolved, resolved._ownerScope)
}
} catch (e) {}
break
}
@ -1356,6 +1363,9 @@ export function inferRuntimeType(
break
}
}
} catch (e) {
// always soft fail on failed runtime type inference
}
return [UNKNOWN_TYPE] // no runtime check
}