1

Does anyone know how to generate a .d.ts from a string, e.g. "export const foo = 42"?

The API reference:

https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API

shows how to generate the compiled .js from a string, but to generate the .d.ts it only gives references for how to do it using a filesystem.

The typescript playground does exactly this, however (and without any network traffic, so it's not writing files on some server and extracting the .d.ts), so it's somehow possible.

1 Answer 1

2

You can override writeFile and readFile of CompilerHost (similar to example in the wiki):

const ts = require("typescript");

const source = "export const foo = 42";
const options = {
  emitDeclarationOnly: true,
  declaration: true,
};

let dts;
const host = ts.createCompilerHost(options);
host.writeFile = (fileName, contents) => (dts = contents);
host.readFile = () => source;

const program = ts.createProgram(["foo"], options, host);
program.emit();

console.log(dts);

"foo" is a fake source file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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