dsherret / ts-type-info

TypeScript AST and code generator [Deprecated]
MIT License
94 stars 8 forks source link

Problem with function createFile() from AST #234

Open f1rstit opened 7 years ago

f1rstit commented 7 years ago

Hello, I want manipulate ast and generate typescript file from this ast but i get this output: var test: [object Object]; My input is simple var test="Hello World";

How i can get good output ?

var ts_type_info = require("ts-type-info");

const fileName = "hello.ts"; const info = ts_type_info.getInfoFromFiles([fileName]); const fileInput = info.getFile(fileName);

const file = ts_type_info.createFile(fileInput); var output = file.write();

console.log(output);

Thanks

dsherret commented 7 years ago

Hmmm... I guess that compiles because FileDefinition matches the structure of what's expected by createFile, but that's not the intended use of createFile.

createFile takes a plain javascript object and turns it into a FileDefinition:

const file = createFile({
    enums: [{
        name: "MyEnum",
        isExported: true
    }]
});

I recommend in this scenario to instead do this:

const fileInput = info.getFile(fileName);

const file = ts_type_info.createFile({});
file.variables.push(fileInput.variables[0]);

Or this:

const fileInput = info.getFile(fileName);
const inputVariable = fileInput.variables[0];

const file = ts_type_info.createFile({});
file.addVariable({
    name: inputVariable.name,
    type: inputVariable.type.text
});

By the way, I'd like to apologise for the lack of documentation for this project. I've started rewriting this library as ts-simple-ast and I'm making documentation more of a priority for that project (see here: https://dsherret.github.io/ts-simple-ast/). At the current moment, file manipulation isn't as good as this library, but it will be more powerful in the future.

f1rstit commented 7 years ago

Thank you for responding quickly. My goal is to make advanced code analysis with database and generate code. I get ast tree data that i will insert into database after i make analysis and update data. After i will generate this updated ast tree but also back to typescript file. I test with escodegen, it works well but not with typescript. I cannot use your solutions because i dont modify ast tree with code. I check already your project ts-simple-ast but i dont find how to do what i need. Is it possible ? Thanks again for your help :)