ts-type-info
TypeScript icon, indicating that this package has built-in type declarations

7.0.1 • Public • Published

TSTypeInfo

npm version Build Status Coverage Status

Simple TypeScript AST and code generator.

Uses the TypeScript Compiler API to get information about TypeScript code in an easy to use format.

npm install ts-type-info --save-dev

Notice - Library Deprecation!

Version 7.0 is the last final major release of ts-type-info that I will work on (feel free to still submit pull requests or bug reports).

There's certain issues with this library and to address them I had to do a complete redesign. I'm working on a more powerful library that supports more use cases: ts-simple-ast. ts-simple-ast wraps the typescript compiler rather than creating separate standalone objects. It's still a work in progress, but it is slowly getting up to speed.

AST

// V:\TestFile.ts

export class MyClass {
    myStringProperty: string;
    readonly myNumberProperty = 253;
 
    myMethod(myParameter: string) {
        return `Test: ${myParameter}`;
    }
}

Get the file info:

import * as TsTypeInfo from "ts-type-info";
 
const result = TsTypeInfo.getInfoFromFiles(["V:\\TestFile.ts"]);
const property = result.getFile("TestFile.ts")
    .getClass("MyClass")                            // get first by name
    .getProperty(p => p.defaultExpression != null); // or first by what matches
 
console.log(property.name);                   // myNumberProperty
console.log(property.type.text);              // number
console.log(property.defaultExpression.text); // 253
console.log(property.isReadonly);             // true
 
// or access the arrays directly
const myMethod = result.files[0].classes[0].methods[0];
 
console.log(myMethod.name); // myMethod

Code Generation

You can work with objects retrieved from the AST or start with your own new file definition:

import * as TsTypeInfo from "ts-type-info";
 
// create whatever you like at the start
const file = TsTypeInfo.createFile({
    classes: [{
        name: "MyClass",
        methods: [{
            name: "myMethod",
            parameters: [{ name: "myParam", type: "string" }],
            onBeforeWrite: writer => writer.write("// myMethod is here"),
            onWriteFunctionBody: writer => {
                writer.write(`if (myParam != null && myParam.length > 40)`).block(() => {
                    writer.write("alert(myParam)");
                });
                writer.newLine().write("return myParam;");
            }
        }]
    }]
});
 
// add to it later
const myClass = file.getClass("MyClass");
myClass.isAbstract = true;
myClass.addDecorator({
    name: "MyDecorator"
});
 
myClass.addProperty({
    name: "myProperty1",
    type: "string"
});
myClass.addProperty({
    name: "myProperty2",
    type: "number",
    defaultExpression: "4"
});
 
// write it out
console.log(file.write());

Outputs:

@MyDecorator
abstract class MyClass {
    myProperty1: string;
    myProperty2 = 4;
 
    // myMethod is here
    myMethod(myParam: string) {
        if (myParam != null && myParam.length > 40) {
            alert(myParam);
        }
 
        return myParam;
    }
}

Simple Examples

  • Strict Interfaces - Make all interface properties required and append "Strict" to the end of the interface name.

Full Examples

  • TsStateTestGenerator - Code generates functions for testing the state of objects. I used this in this ts-type-info and was able to discover a bunch of unreported bugs. I also no longer have to maintain a large portion of the project because the code is automatically generated for me. I highly recommend this.
  • TsCloneableGenerator - Code generates functions for cloning and filling objects.
  • TsObjectCreate - Code generates functions for creating objects with their types.
  • Server Bridge - Automatically generates client side code to communicate with the server from the server side code.

Include tsNodes

In case there's something you need from the compiler that's not implemented in this library, set the includeTsNodes option to true. This will include the TypeScript compiler nodes in the tsNode property of most objects.

import * as ts from "typescript";
import * as TsTypeInfo from "ts-type-info";
 
const result = TsTypeInfo.getInfoFromFiles(["V:\\TestFile.ts"], { includeTsNodes: true });
const typeChecker = result.getTypeChecker(); // ts.TypeChecker in case you need it
const myMethod = result.getFile("TestFile.ts").getClass("MyClass").getMethod("myMethod");
const myMethodNode = myMethod.tsNode as ts.MethodDeclaration;
 
console.log(myMethodNode.body.statements[0].getText()); // "return `Test: ${myParameter}`;"

Package Sidebar

Install

npm i ts-type-info

Weekly Downloads

11

Version

7.0.1

License

MIT

Last publish

Collaborators

  • dsherret