Contributing TS Type Declarations to Open Source Projects
·
1 min read
·
201
Words
·
-Views
-Comments
I recently authored Redux typings for an open-source project and noted the key takeaways so I can repeat the process faster next time.
Why declaration files matter
- They power editor niceties such as auto-complete and inline API hints.
- They give downstream consumers type safety.
Ways to create and ship declaration files
- Write your library in TypeScript and compile with
tsc --declaration
. The compiler emits both the.js
output and the matching.d.ts
files. - Hand-write
.d.ts
files. This is common for inactive packages that cannot ship types themselves. Publish them to DefinitelyTyped so consumers can install@types/<package>
. - Keep local
.d.ts
files inside a project and point to them viatypes
ortypeRoots
intsconfig.json
.
Common questions
- How do I reference another library’s types? Import them directly inside the declaration file.
- How do I describe generator functions? Use the
Generator
return type instead offunction*
syntax in the declaration. - How do I declare exported variables? Declare them explicitly, for example
export const foo: Foo;
inside the.d.ts
.
Sample code
The typings I contributed live here: https://github.com/adobe/redux-saga-promise
Final Thoughts
Declaration files feel tedious the first time around, but once you understand the patterns, adding typings to open-source projects becomes straightforward.