Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share an interface between two apps?

What mechanism for sharing can I put in place to allow two separate typescript projects to communicate along common interfaces?

The basic idea is that I have one main project that will implement the interfaces, and there will be another project that consumes them. However I don't want either of the projects to be dependent on the other.

Specifically: How can I can create and distribute a library of contracts (and perhaps any functionality that complements them if applicable). Are there any established or emerging conventions in the TypeScript ecosystem to distribute libraries of interfaces via NPM?

like image 868
Alexander Trauzzi Avatar asked Mar 11 '15 17:03

Alexander Trauzzi


3 Answers

Just define the interface in a separate file, or collect all shared interfaces in a file interfaces.ts (or a interfaces.d.ts). Both projects can reference this file, you can have copies of that file in both projects.

TypeScript is not like i.e. C# where you have to reference an underlying assembly (although this will be fixed in C# with assembly neutral interfaces).

But beware: TypeScript has no dedicated runtime that assures your interfaces match. As everything is still JavaScript, at runtime you have to make sure the interfaces match. If one projects uses i.e. another version of the interfaces with properties that didn't exist in previous versions, you will still run into trouble.

like image 55
Dynalon Avatar answered Nov 11 '22 13:11

Dynalon


Several years and many projects later, the simplest answer to this question today is to simply publish a .d.ts to an npm package and consume it! This project can be built from typescript sources and even include built code.

Of course, a lot of this answer now is long after TypeScript and the JS community have matured and come together to establish these conventions.

like image 31
Alexander Trauzzi Avatar answered Nov 11 '22 13:11

Alexander Trauzzi


Are there any established or emerging conventions in the TypeScript ecosystem to distribute libraries of interfaces via NPM

Use the typescript key in your package.json to point to the definition file :

https://github.com/DefinitelyTyped/tsd#link-to-bundled-definitions

like image 3
basarat Avatar answered Nov 11 '22 13:11

basarat