5

TypeScript API Program has method getSyntacticDiagnostics to get syntactic errors. But if there is no Program, just SourceFile how can I get the same kind of information?

I created SourceFile through

function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;

1 Answer 1

4

Remember that fileName (string) parameter in createSourceFile is virtual file name. This fileName (string) is used globaly while using TypeScript library.

The most important thing what you need is what doc comment on createProgam method says. A Program is an immutable collection of 'SourceFile's and a 'CompilerOptions' that represent a compilation unit. createProgam method as first parameter requires list of strings which are virtual names of files used in this program.

If you don't understand previous 2 theoretical paragraphs I think that comments in sample will help you.

// this is the real code of file. Use fs.readFile, fs.readFileSync or something other to load file real source code.
var code = "class 1X {}";

// I will use this virtual name to reference SourceFile while working with TypeScript API.
var virtualFileName = "aaa.ts";

// initialize SourceFile instance
var sf = ts.createSourceFile(virtualFileName, code, ts.ScriptTarget.ES5);

// Make program as collection of my one virtual file
var prog = ts.createProgram([virtualFileName], {});

// process response as you need.
console.log(prog.getSyntacticDiagnostics(sf));
Sign up to request clarification or add additional context in comments.

1 Comment

If you get errors about Cannot read property 'text' of undefined then you may also want to add the fourth parameter (setParentNodes) to createSourceFile, i.e. ts.createSourceFile(virtualFileName, code, ts.ScriptTarget.ES5, true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.