In order to extract the type signature, you'll need to use the compiler API. Assuming you have a file:
// ./src/my-file.ts
type TypeA = {
prop1: string;
prop2: number;
}
type TypeB = Omit<TypeA, "prop2">;
from a script outside your project root:
// ./type-printer.ts
import * as ts from "typescript";
function extractTypeSignature(filename: string, aliasName: string): string {
const program: ts.Program = ts.createProgram([ filename ], { emitDeclarationOnly: true });
const sourceFile: ts.SourceFile = program.getSourceFile(filename);
const typeChecker: ts.TypeChecker = program.getTypeChecker();
// Get the declaration node you're looking for by it's type name.
// This condition can be adjusted to your needs
const statement: ts.Statement | undefined = sourceFile.statements.find(
(s) => ts.isTypeAliasDeclaration(s) && s.name.text === aliasName
);
if (!statement) {
throw new Error(`Type: '${aliasName}' not found in file: '${filename}'`);
}
const type: ts.Type = typeChecker.getTypeAtLocation(statement);
const fields: string[] = [];
// Iterate over the `ts.Symbol`s representing Property Nodes of `ts.Type`
for (const prop of type.getProperties()) {
const name: string = prop.getName();
const propType: ts.Type = typeChecker.getTypeOfSymbolAtLocation(prop, statement);
const propTypeName: string = typeChecker.typeToString(propType);
fields.push(`${name}: ${propTypeName};`);
}
return `type ${aliasName} = {\n ${fields.join("\n ")}\n}`;
}
const typeBSignature = extractTypeSignature("./src/my-file.ts", "TypeB");
// write to file or console log
console.log(typeBSignature);
/*
type TypeB = {
prop1: string;
}
*/
I've explicitly annotated all variables to show where the types are coming from. Even though it's a small script, I'd recommend writing compiler scripts in TypeScript rather than JavaScript and executing with tsc file.ts && node file.js or using something like ts-node, as the type inference/typeguards are very useful when navigating the compiler API.
console.log("value_you_want_to_see");jsonschema-definer