1 | import * as tsm from 'ts-morph';
|
2 | import { log } from '../utils/log';
|
3 |
|
4 | export type TypeChecker = ({
|
5 | declaration,
|
6 | }: {
|
7 | declaration: tsm.Node;
|
8 | }) => string;
|
9 |
|
10 | export function getTypeChecker({
|
11 | project,
|
12 | }: {
|
13 | project: tsm.Project;
|
14 | }): TypeChecker {
|
15 | const projectTypeChecker = project.getTypeChecker();
|
16 |
|
17 | return ({ declaration }) => {
|
18 | let type = 'any';
|
19 |
|
20 | try {
|
21 | const typeChecker = projectTypeChecker.compilerObject;
|
22 | const { compilerNode } = declaration;
|
23 | const nodeType = typeChecker.getTypeAtLocation(compilerNode);
|
24 | type = typeChecker.typeToString(
|
25 | nodeType,
|
26 | compilerNode,
|
27 | tsm.ts.TypeFormatFlags.NoTruncation |
|
28 | tsm.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope
|
29 | );
|
30 | } catch (err) {
|
31 |
|
32 | log('type checker: error: %O', { err });
|
33 | }
|
34 |
|
35 | return type;
|
36 | };
|
37 | }
|