Reputation:
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.
Upvotes: 1
Views: 370
Reputation: 37918
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.
Upvotes: 2