Contributing TS Type Declarations to Open Source Projects
Contributing TS Type Declarations to Open Source Projects
Sep 12, 2021
·
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.jsoutput and the matching.d.tsfiles. - Hand-write
.d.tsfiles. This is common for inactive packages that cannot ship types themselves. Publish them to DefinitelyTyped so consumers can install@types/<package>. - Keep local
.d.tsfiles inside a project and point to them viatypesortypeRootsintsconfig.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
Generatorreturn 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.

