ts-type-info icon indicating copy to clipboard operation
ts-type-info copied to clipboard

Problem with function createFile() from AST

Open f1rstit opened this issue 8 years ago • 2 comments

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

f1rstit avatar Apr 10 '17 15:04 f1rstit

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.

dsherret avatar Apr 10 '17 21:04 dsherret

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 :)

f1rstit avatar Apr 11 '17 12:04 f1rstit