npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-type-info

v7.0.1

Published

Reflection and code generation in TypeScript.

Downloads

73

Readme

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}`;"