TypeScript for Library Authors: Harnessing the Power of TypeScript for DX

Rate this content
Bookmark
The video discusses the advantages of using TypeScript for library authors, focusing on improving code quality, covering edge cases, and facilitating refactoring. TypeScript documentation is integrated into the code, providing up-to-date information directly in the IDE. Testing TypeScript types ensures accuracy, and tools like Unbuild and API Extractor are recommended. The importance of versioning types to avoid breaking user code is highlighted, and strategies for handling type changes are provided. The talk emphasizes using TypeScript for accurate function return values and leveraging type inference. Nuxt's use of TypeScript for automatic type detection in components and plugins is also covered.

From Author:

Using real-life open-source examples, we'll explore the power of TypeScript to improve your users' experience. We'll cover best practices for library authors, as well as tips and tricks for how to take a library to the next level. This talk will cover: 


- how to leverage the type inference to provide help to your users; 

- using types to reduce the need and complexity of your documentation - for example, using function overloads, string literal types, and helper (no-op) functions; 

- setting up testing to ensure your library works (and your types do too!) with tools like tsd and expect-type; 

- treating types as an API and reducing breaking changes whilst shipping enhancements; 

- I'd draw on my experience with libraries like nuxt3, sanity-typed-queries and typed-vuex and show what we managed to do and what I'd do differently in future. 

This talk has been presented at TypeScript Congress 2022, check out the latest edition of this Tech Conference.

FAQ

The speaker is Daniel Rowe, a member of the Nuxt core team based in the northeast of the UK. He maintains several open-source packages and has a strong interest in improving developer experience.

TypeScript helps improve code quality by covering edge cases, facilitating refactoring, and providing accurate documentation. It offers a true-to-life representation of how libraries work, enhancing the developer experience.

TypeScript types and TS doc (or JS doc) can serve as accurate, up-to-date documentation embedded directly in the code. This approach ensures users get the correct information for the version they are using without needing a separate documentation site.

Expect type and ts-expect-error are recommended for testing TypeScript types. These tools help ensure that the types are accurate and behave as expected.

Versioning TypeScript types is crucial because changes in types can break user code. Adhering to semantic versioning (semver) helps manage these changes and ensures users are aware of any potential breaking changes.

The 'fountain of truth' paradigm suggests allowing TypeScript to infer return types from the actual code, rather than manually declaring them. This approach helps ensure the types are accurate and reduces the risk of errors.

Types can be used to accurately describe the expected inputs and outputs of functions, enhancing the usability and reliability of the library. For example, using string literals instead of generic strings can provide more specific and useful information to the user.

Type inference allows TypeScript to deduce the types of variables and return values automatically. This feature is particularly useful for creating accurate and maintainable types, especially in complex libraries.

Nuxt uses TypeScript to provide automatic type detection for components, plugins, API routes, and more. This integration ensures that developers get accurate type information and support directly in their IDEs.

You can contact Daniel Rowe via email or Twitter for more information. He is also active on the Nuxt Discord server, where you can ping him directly with any questions.

Daniel Roe
Daniel Roe
25 min
29 Apr, 2022

Comments

Sign in or register to post your comment.

Video Transcription

1. Introduction to TypeScript for Library Authors

Short description:

TypeScript for library authors offers benefits for both internal and external use. Internally, it helps improve code quality, cover edge cases, and facilitate refactoring. Externally, it provides users with an accurate understanding of how libraries work, offering a true-to-life representation of their functionality. TypeScript allows users to gain insight into libraries and understand the expected behavior of function calls.

Hello. It's a pleasure to be here today, talking about TypeScript for library authors. It's dear to my heart because I'm self interested and love using libraries with great developer experience, and I'm sure you do as well.

My name is Daniel Rowe. I'm based in the northeast of the UK, and I'm on the Nuxt core team, and I maintain a few other open source packages as well. I should say in advance, this is my perspective as we dive into TypeScript for library authors, you may have other ideas. You may have better approaches, and I'd love to hear from you if that's the case. Please do contact me, either by email or Twitter is a great way to make contact. Please. I'd love to connect later.

So, to start with, the question I'd like to pose is what's the point of TypeScript for library authors, I guess. And obviously, even if you weren't exposing your types outside of your own project, I think there would still be benefit. I certainly would find that there would be myself. I think TypeScript helps improve the code that we produce. It helps us cover edge cases. It helps us see the possible alternatives and outcomes of what we're creating. And it helps with things like refactoring, making sure we haven't left something out. Lots of huge benefits for using TypeScript internally.

But I think looking at the question of why we use TypeScript for external benefit, the key reason is truth. And I think there are a couple of different implications for this that I hope to go through today. But I think it all comes back to truth. We're allowing our users a window into how our libraries work. That window is accurate. It needs to be accurate. We're offering them an alternative to looking at our source code or reading our documentation. Something that is actually a true-to-life representation of what is happening. And that I think is one of the things that makes TypeScript so amazing, when you're using it as you consume some other library. Because you're getting insight through it. Your IDE popup is telling you something about how it works under the hood. It's telling you something about what you can expect to come back from that function call.

2. Documentation and Examples in Code

Short description:

Types are part of your documentation. API documentation and examples should be in your code. Users get up-to-date information when using your library. No need for a separate website. You can add links, examples, default values, and version information. Mature standards like jsdoc provide a great way to see documentation in your IDE. You can even host it using tools like jsdocs.io or unpiped.

The possible options you can pass to it. That kind of thing. It's all about truth for me. And the first implication is documentation. That's about truth as well, isn't it? So types are part of your documentation or maybe even your documentation. Certainly, types and TS doc, JS doc, I'll use the terms interchangeably even though they're not exactly. But they can provide your library documentation.

So if you think of adding comments immediately before every function, every interface, every constant that you expose from your library, you can actually accurately describe that there. My hot take for today is all of your API documentation and examples should be in your code. It means that when your users are actually using your library, they get up to date, accurate information about the version that they are consuming at that moment in time. You don't have to have a fancy website with a drop down allowing users to select major versions, if your documentation is actually in the code itself. Their editor will surface the correct version for them. You can add links. You can add examples. You have the full power of markdown at your disposal. You can add default values. You can add the version something was introduced to the project at. Anything else that you might think or consider, jsdoc, they're really mature standards. And there's nothing quite that beats being able to see the documentation for what you're using in your IDE rather than having to go somewhere else or perform a quick search. You can even host it that way. Check out jsdocs.io. You can actually type any package in, and they'll render up documentation for you based on the declaration files for that project. You might even consider something like unpiped which is a package in the onjs.github organization which enables you to have a typed configuration schema. It might not be relevant for your project, we use it in Nuxt. We are able to type our configuration schema, and then that can be exported to json or to code. We can do things with it, such as generate documentation programmatically. That is what we use to ensure our Nuxt config documentation is accurate and updated on the website. It is always based on the actual code and the JSTOC in that code file.

Here is just a little example picked from a library I maintain. It is not complex, it is not difficult as an author to do this.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Full Stack Documentation
JSNation 2022JSNation 2022
28 min
Full Stack Documentation
Top Content
The Talk discusses the shift to full-stack frameworks and the challenges of full-stack documentation. It highlights the power of interactive tutorials and the importance of user testing in software development. The Talk also introduces learn.svelte.dev, a platform for learning full-stack tools, and discusses the roadmap for SvelteKit and its documentation.
Welcome to Nuxt 3
Vue.js London Live 2021Vue.js London Live 2021
29 min
Welcome to Nuxt 3
Top Content
Nux3 has made significant improvements in performance, output optimization, and serverless support. Nuxt Bridge brings the Nitro engine for enhanced performance and easier transition between Nuxt 2 and Nuxt Read. Nuxt 3 supports Webpack 5, Bytes, and Vue 3. NextLab has developed brand new websites using Docus technology. Nuxt.js is recommended for building apps faster and simpler, and Nuxt 2 should be used before migrating to Nuxt 3 for stability. DOCUS is a new project that combines Nuxt with additional features like content modules and an admin panel.
React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
Watch video: React's Most Useful Types
Today's Talk focuses on React's best types and JSX. It covers the types of JSX and React components, including React.fc and React.reactnode. The discussion also explores JSX intrinsic elements and react.component props, highlighting their differences and use cases. The Talk concludes with insights on using React.componentType and passing components, as well as utilizing the react.element ref type for external libraries like React-Select.
TypeScript and React: Secrets of a Happy Marriage
React Advanced Conference 2022React Advanced Conference 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
React and TypeScript have a strong relationship, with TypeScript offering benefits like better type checking and contract enforcement. Failing early and failing hard is important in software development to catch errors and debug effectively. TypeScript provides early detection of errors and ensures data accuracy in components and hooks. It offers superior type safety but can become complex as the codebase grows. Using union types in props can resolve errors and address dependencies. Dynamic communication and type contracts can be achieved through generics. Understanding React's built-in types and hooks like useState and useRef is crucial for leveraging their functionality.
Remix Flat Routes – An Evolution in Routing
Remix Conf Europe 2022Remix Conf Europe 2022
16 min
Remix Flat Routes – An Evolution in Routing
Top Content
Remix Flat Routes is a new convention that aims to make it easier to see and organize the routes in your app. It allows for the co-location of support files with routes, decreases refactor and redesign friction, and helps apps migrate to Remix. Flat Folders convention supports co-location and allows importing assets as relative imports. To migrate existing apps to Flat Routes, use the Remix Flat Routes package's migration tool.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
Top Content
Daniel Rowe discusses building a TypeScript-first framework at TypeScript Congress and shares his involvement in various projects. Nuxt is a progressive framework built on Vue.js, aiming to reduce friction and distraction for developers. It leverages TypeScript for inference and aims to be the source of truth for projects. Nuxt provides type safety and extensibility through integration with TypeScript. Migrating to TypeScript offers long-term maintenance benefits and can uncover hidden bugs. Nuxt focuses on improving existing tools and finds inspiration in frameworks like TRPC.

Workshops on related topic

React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Featured Workshop
Josh Goldberg
Josh Goldberg
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced Conference 2022React Advanced Conference 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Building Your Own Custom Type System
React Summit 2024React Summit 2024
38 min
Building Your Own Custom Type System
Featured Workshop
Kunal Dubey
Kunal Dubey
I'll introduce the audience to a concept where they can have end-to-end type systems that helps ensure typesafety across the teams Such a system not only improves communication between teams but also helps teams collaborate effectively and ship way faster than they used to before. By having a custom type system, teams can also identify the errors and modify the API contracts on their IDE, which contributes to a better Developer Experience. The workshop would primarily leverage TS to showcase the concept and use tools like OpenAPI to generate the typesystem on the client side. 
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.