Вопрос

Setup
Lets say that we have two files, A.ts and B.d.ts. Now inside A we have:

class A implements B{...}

Now lets say I want to combine all my typescript files into a singular definition file. The only way I know of how to do this is to create a .js file and then also a resultant .d.ts file.

Therefore we do:

tsc --out foo.js --declaration B.d.ts A.ts

We get foo.js, and foo.d.ts.

Now the only issue is that foo.d.ts only contains the definition for A.ts and not for B.d.ts. So to get our generated foo.d.ts to actually work and not throw errors we need to add a manual reference to B.d.ts OR we need to copy and paste the entire contents of B.d.ts into foo.d.ts.

Both solutions are rather ugly. So is there a way to create a singular declaration file via the typescript compiler that will also include user created interfaces? I must be missing something...

Это было полезно?

Решение

The behaviour is by design, it is intended to make writing library extensions and managing dependencies a bit easier. For example, if you were writing a jQuery plugin, you would want your .d.ts file to contain all of your definitions, but not the jQuery definitions. For this reason the compiler won't add anything from "external" .d.ts files into the combined .d.ts file you generate.

If it did include these definitions, it would cause duplicate definition errors when people combine multiple libraries (i.e. the jQuery definitions would be duplicated in every plugin definition).

If you want code included in your single compiled .d.ts file, it needs to originate from a .ts file without the d-prefix. This does mean adding the declare keyword to modules / classes inside the file - but actually that may become a requirement in version 0.9 anyway even for .d.ts files so that isn't much overhead.

In essence, you could think of the file extensions as follows:

  • .ts files are internal to the program
  • .d.ts files are external dependencies

Другие советы

Use B.ts instead of B.d.ts

You can see a sample here : https://github.com/basarat/ts-test/tree/master/tests/compileToSingle

My out.d.ts https://github.com/basarat/ts-test/blob/master/tests/compileToSingle/out.d.ts contains the interface from dec.ts: https://github.com/basarat/ts-test/blob/master/tests/compileToSingle/dec.ts

My out.d.ts did not contain the interface : https://github.com/basarat/ts-test/blob/34eeb54618e57765ea0e2f9ce0c48ebd7f46942a/tests/compileToSingle/out.d.ts If I had a dec.d.ts : https://github.com/basarat/ts-test/blob/34eeb54618e57765ea0e2f9ce0c48ebd7f46942a/tests/compileToSingle/dec.d.ts

You can use the declare keyword for your classes / variables etc. in .ts Do not use declare for interfaces as that breaks in TS > 0.9

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top