Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate only a .d.ts from a single typescript file?

Tags:

typescript

I want to create a single .d.ts file for a single .ts file without also creating a .js file(s) from my source .ts file(s).

I want to run something like:

$ tsc myFile.ts -d

But have the result be only myFile.ts's generated .d.ts file.

Currently, the result is that that file and all of the .ts files in my project produce their own .js and .d.ts files.

My target is es2015, so the module option should be defaulting to CommonJS (if that matters).

like image 422
Kevin Beal Avatar asked Aug 04 '17 21:08

Kevin Beal


1 Answers

I want to create a single .d.ts file for a single .ts file without also creating a .js file(s) from my source .ts file(s).

While there is no compiler option for that, we can contain and delete the resultant .js files.

Case 1: A single .ts file that does not import local .ts files

What we can do is

  1. assign . as the declaration directory,
  2. assign temp as the JavaScript directory, and
  3. delete the temp directory after transpiling.

    tsc --declaration --declarationDir . --outDir temp foo.ts
    rm -rf temp
    

That works if foo.ts does not import other, local .ts files. When foo.ts does import other, local .ts files, the compiler creates a separate .d.ts file for each. Since that is not what we want right now, what follows is better.

Case 2: A single .ts file that imports local .ts files

If our use case allows creating system or amd style declaration files, we can do this:

tsc foo.ts --outFile foo.js --declaration --module system
rm -rf foo.js

The Result in Both Cases

Both of those approaches generate the same directory structure with different declaration file syntax.

bar
  bar.ts
foo.d.ts           <---- a single declaration file
foo.ts
tsconfig.json
like image 113
Shaun Luttin Avatar answered Sep 24 '22 13:09

Shaun Luttin