1
votes

I am making an npm module with typescript which has a few interfaces. In the index.ts file, I export all the classes and interfaces. I declared the interfaces as "interface dto {a:string;} export default dto".

Now in the index.ts, I import the interface and do { dto: dto }

When it transpiles, its gone.

How can I expose interfaces outside of the npm module?

2
You can use tsc -d option to generate type declarations and distribute generated d.ts filesartem

2 Answers

1
votes

When it transpiles, its gone.

If you don't use an import it is erased. This is intentionally so that you don't take a runtime dependency on a module if its only used for compile time type analysis.

More

Covered here as well : https://basarat.gitbooks.io/typescript/content/docs/project/external-modules.html#import-type-only

0
votes

Whilst interfaces are a key feature of TypeScript, they do not translate to native JavaScript...

TypeScript uses interfaces to provide build-time type safety. But these interfaces are akin to a "duck test" (if it quacks then it must be a duck), and are not equivalent to interfaces in other strongly-typed languages wherein a class will explicitly implement an interface. Rather TypeScript allows you to use interfaces instead of classes.

Transpiling is a process of cross-compiling from TypeScript to JavaScript so that code can run in native JS engines (e.g. in a browser).

The benefit of TypeScript interfaces is only felt when writing/compiling code. Once compiled, there is no JavaScript equivalent and these interfaces disappear.

However, there is a TypeScript convention for importing declarations (from a .d.ts) which convey much the same meaning about your resultant JavaScript code, and therefore allowing a TS consumer of your JS to benefit from the same strong-typing.

Basarat already provided a link to his excellent book, but I believe he misinterpreted the question, and that this link answers it better:

https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.html