Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print TypeScript types into console / file

I have multiple types that form a larger, complex type that currently is used on my server. Is it possible to print the larger, complex type into console / file?

Example

type TypeA = {
  prop1: string;
  prop2: number;
}

type TypeB = Omit<TypeA, "prop2">;

console.logType(TypeB);
// {
//   prop1: string;
// }
like image 202
SILENT Avatar asked Jul 21 '26 09:07

SILENT


1 Answers

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.

like image 133
chrisbajorin Avatar answered Jul 23 '26 00:07

chrisbajorin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!