Skip to content

Commit 620be21

Browse files
Simplify type string generation (#44)
1 parent 6409355 commit 620be21

File tree

3 files changed

+9
-7
lines changed

3 files changed

+9
-7
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@joernio/astgen",
3-
"version": "3.32.0",
3+
"version": "3.33.0",
44
"description": "Generate JS/TS AST in json format with Babel",
55
"exports": "./index.js",
66
"keywords": [

src/Defaults.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,5 +95,7 @@ export const DEFAULT_TSC_OPTIONS: tsc.CompilerOptions = {
9595
export const DEFAULT_TSC_TYPE_OPTIONS: number = tsc.TypeFormatFlags.NoTruncation | tsc.TypeFormatFlags.InTypeAlias
9696

9797
export const ANY: string = "any"
98+
export const UNKNOWN: string = "unknown"
9899

99-
export const DEFAULT_IGNORED_TYPES: string[] = ["any", "unknown", "any[]", "unknown[]"]
100+
export const STRING_REGEX: RegExp = /^["'`].*["'`]$/
101+
export const ARRAY_REGEX: RegExp = /.+\[]$/

src/TscUtils.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import * as Defaults from "./Defaults";
2-
import {DEFAULT_IGNORED_TYPES} from "./Defaults";
32

43
import tsc from "typescript";
54

@@ -17,9 +16,10 @@ function forEachNode(ast: tsc.Node, callback: (node: tsc.Node) => void): void {
1716
function safeTypeToString(node: tsc.Type, typeChecker: tsc.TypeChecker): string {
1817
try {
1918
const tpe: string = typeChecker.typeToString(node, undefined, Defaults.DEFAULT_TSC_TYPE_OPTIONS);
20-
if (/^["'`].*["'`]$/.test(tpe)) {
21-
return "string";
22-
}
19+
if (tpe.length === 0) return Defaults.ANY
20+
if (tpe == Defaults.UNKNOWN) return Defaults.ANY
21+
if (Defaults.STRING_REGEX.test(tpe)) return "string";
22+
if (Defaults.ARRAY_REGEX.test(tpe)) return "__ecma.Array";
2323
return tpe;
2424
} catch (err) {
2525
return Defaults.ANY;
@@ -51,7 +51,7 @@ export function typeMapForFile(file: string): TypeMap {
5151
} else {
5252
typeStr = safeTypeToString(typeChecker.getTypeAtLocation(node), typeChecker);
5353
}
54-
if (!DEFAULT_IGNORED_TYPES.includes(typeStr)) {
54+
if (typeStr !== Defaults.ANY) {
5555
const pos = `${node.getStart()}:${node.getEnd()}`;
5656
seenTypes.set(pos, typeStr);
5757
}

0 commit comments

Comments
 (0)