TS: Guard getTypeAtLocation with try/catch

This commit is contained in:
Asger F
2020-01-02 16:31:23 +00:00
parent 0388e9ca0c
commit 202746e92d
2 changed files with 24 additions and 1 deletions

View File

@@ -67,6 +67,17 @@ function forEachNode(ast: ts.Node, callback: (node: ts.Node) => void) {
visit(ast);
}
function tryGetTypeOfNode(typeChecker: ts.TypeChecker, node: AugmentedNode): ts.Type | null {
try {
return typeChecker.getTypeAtLocation(node);
} catch (e) {
let sourceFile = node.getSourceFile();
let { line, character } = sourceFile.getLineAndCharacterOfPosition(node.pos);
console.warn(`Could not compute type of ${ts.SyntaxKind[node.kind]} at ${sourceFile.fileName}:${line+1}:${character+1}`);
return null;
}
}
export function augmentAst(ast: AugmentedSourceFile, code: string, project: Project | null) {
ast.$lineStarts = ast.getLineStarts();
@@ -196,7 +207,7 @@ export function augmentAst(ast: AugmentedSourceFile, code: string, project: Proj
let contextualType = isContextuallyTypedNode(node)
? typeChecker.getContextualType(node)
: null;
let type = contextualType || typeChecker.getTypeAtLocation(node);
let type = contextualType || tryGetTypeOfNode(typeChecker, node);
if (type != null) {
let parent = node.parent;
let unfoldAlias = ts.isTypeAliasDeclaration(parent) && node === parent.type;

View File

@@ -0,0 +1,12 @@
| bar.ts:1:10:1:10 | A | any |
| bar.ts:1:10:1:10 | A | any |
| bar.ts:1:19:1:29 | "@blah/foo" | any |
| bar.ts:3:5:3:5 | x | any |
| node_modules/@blah/foo/index.d.ts:1:8:1:15 | FooArray | typeof FooArray in library-tests/TypeScript/RegressionTests/ImportSelf/node_modules/@blah/foo/index.d.ts |
| node_modules/@blah/foo/index.d.ts:1:20:1:20 | A | any |
| node_modules/@blah/foo/index.d.ts:1:20:1:20 | A | any |
| node_modules/@blah/foo/index.d.ts:1:29:1:39 | '@blah/foo' | any |
| node_modules/@blah/foo/index.d.ts:3:11:3:18 | FooArray | typeof FooArray in library-tests/TypeScript/RegressionTests/ImportSelf/node_modules/@blah/foo/index.d.ts |
| node_modules/@blah/foo/index.d.ts:4:12:4:15 | blah | () => void |
| node_modules/@blah/foo/index.d.ts:8:10:8:10 | A | any |
| node_modules/@blah/foo/index.d.ts:8:10:8:10 | A | any |