Contributing TS Type Declarations to Open Source Projects

How to create, package, and reference TypeScript declaration files when contributing typings to open-source projects.

Sep 12, 2021 · 1 min read · 201 Words · -Views -Comments · Programming
TypeScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

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