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

  1. They power editor niceties such as auto-complete and inline API hints.
  2. They give downstream consumers type safety.

Ways to create and ship declaration files

  1. Write your library in TypeScript and compile with tsc --declaration. The compiler emits both the .js output and the matching .d.ts files.
  2. 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>.
  3. Keep local .d.ts files inside a project and point to them via types or typeRoots in tsconfig.json.

Common questions

  1. How do I reference another library’s types? Import them directly inside the declaration file.
  2. How do I describe generator functions? Use the Generator return type instead of function* syntax in the declaration.
  3. 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.

References

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover