Are the (module) types wrong?

Rate this content
Bookmark
GithubProject website

Have you ever installed a dependency, imported it just like the README instructs, and immediately been met with strange TypeScript errors about default imports, the output module format, or ESM/CommonJS interoperability? When everything works at runtime but TypeScript complains, you might wonder, is this a TypeScript bug? Or… are the types wrong?


The JavaScript module and package publishing landscape is complicated. Nearly one third of the most popular types-included npm packages have some sort of module-related typings issue that can cause confusion for users. But things are starting to improve. In this talk, we’ll:

- explore how we got here—why are things complicated?
- develop a simple and accurate mental model for how TypeScript sees packages
- see how the `arethetypeswrong` tool can help catch issues before publishing
- look at trends in the `arethetypeswrong` data for popular packages over time
- discuss next steps for making the typed package ecosystem better

FAQ

ESM stands for ECMAScript Module, which is a module system added to the JavaScript language specification in 2015, recognized by the import and export keywords.

CommonJS, or CJS, is a community standard module system popularized by Node before ECMAScript Modules (ESM) existed. It uses require and module.exports for managing dependencies, unlike ESM which uses import and export.

Node.js uses the file extension to determine the module format. A .mjs file is always treated as ESM, a .cjs file is always CommonJS, and a .js file's format is determined by the nearest package JSON's type module field.

Declaration files in TypeScript, with a .d.ts extension, contain type information about the corresponding JavaScript files. They are important because they inform the TypeScript compiler about the structure and types of JavaScript files, aiding in type checking and editor support.

The 'type module' field in package.json specifies that .js files in the directory are to be treated as ECMAScript modules (ESM) by Node.js, differentiating them from CommonJS modules.

When importing a CommonJS module as ESM in Node, the default import will not directly retrieve the exported value. Instead, it retrieves an object with a 'default' property that holds the exported value, due to the module format mismatch.

The 'exports' field in package.json provides an encapsulation mechanism for module resolution, specifying which files can be imported by consumers of the package and under what conditions, enhancing security and usability of packages.

The 'trace resolution' flag in TypeScript (TSC) provides detailed information about the file and module resolution process during compilation, helping developers understand how TypeScript resolves module paths and detects files.

The 'Are the types wrong' tool is a utility that analyzes NPM packages to identify discrepancies between the types declared by TypeScript and the actual JavaScript files, helping maintainers and developers ensure consistency between types and runtime behavior.

Andrew Branch
Andrew Branch
30 min
21 Sep, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk discusses module system complexities and terminology, TypeScript and Node disagreements, and fixing TypeScript errors with the Helmet package. It also explores module resolution and type disagreements, challenges with TypeScript and Node support, and the need for improvements in popular packages.

1. Introduction to Modules and Terminology

Short description:

Hello, everyone. My name is Andrew and I've been on the TypeScript team for about the last four years. Today, we'll be discussing module system complexities and the terminology associated with it, such as ESM and common JS. It's important to be familiar with module resolution options and the differences between Node.16 and Node.Next.

All right. Hello, everyone. And thanks for joining me to talk about modules. My name is Andrew. I've been on the TypeScript team for about the last four years, and we have a lot to talk about today in a short amount of time, so that's enough about me. And I think we all know that module system complexities are super interesting and super fun, so no time to sell you on it, but if you watched Mark Erickson's talk and couldn't get enough, this is definitely the talk for you.

So before we get started, there is a little bit of terminology we should cover. I'm going to use the term ESM or the acronym ESM about a hundred times in this talk. That stands for ECMAScript module. ESM is the module system that was added to the JavaScript language specification itself in 2015. And you can recognize it by the import and export keywords. The other module system we'll discuss is common JS or CJS. That's the community standard that was popularized by Node before ESM existed. If you've ever seen require and module.exports, that's common JS and it's still supported by Node.

I'm also going to have to say a few file extensions during this talk. And since those can overlap with other acronyms, I'll try really hard to remember to pronounce them with a dot at the beginning. It will be somewhat helpful if you're at least vaguely familiar with some module resolution options and typescripts. Node.16 and Node.Next are currently identical, so I might call them by either name. They're the only good choice for modern Node, and they don't just mean emitting ES modules. That's a common misconception. Historically, the one called Node was what everyone used for pretty much everything, but it really hasn't kept up with modern features.

2. Understanding the Typescript Error with Helmet

Short description:

We're going to take a look at a confusing typescript error with the NPM dependency Helmet. When compiling down to common JS, everything runs fine. However, when switching to ES modules, an error occurs where helmet isn't callable anymore. Let's investigate further by running the code.

We're going to take a look at a bit of a confusing typescript error here. I'm looking at the NPM dependency called Helmet. I've just copied and pasted the README example here. This builds with TSC and runs in Node just fine. You can see that I'm currently compiling down to common JS. If I want to move to ES modules here, I can do that by adding the type module field to my own package JSON for the project. But when I do that and come back here, I'm now getting this confusing typescript error that says helmet isn't callable anymore. If I mess around with this enough, I'll see typescript I'm running. This doesn't look right to me, but let's run it and see what happens.

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

Vite: Rethinking Frontend Tooling
JSNation Live 2021JSNation Live 2021
31 min
Vite: Rethinking Frontend Tooling
Top Content
Vite is a new build tool that intends to provide a leaner, faster, and more friction-less workflow for building modern web apps. This talk will dive into the project's background, rationale, technical details and design decisions: what problem does it solve, what makes it fast, and how does it fit into the JS tooling landscape.
Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
Do you have a large product built by many teams? Are you struggling to release often? Did your frontend turn into a massive unmaintainable monolith? If, like me, you’ve answered yes to any of those questions, this talk is for you! I’ll show you exactly how you can build a micro frontend architecture with Remix to solve those challenges.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced Conference 2023React Advanced Conference 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
React provides a contract to developers- uphold certain rules, and React can efficiently and correctly update the UI. In this talk we'll explore these rules in depth, understanding the reasoning behind them and how they unlock new directions such as automatic memoization. 
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
Remix is a web framework that gives you the simple mental model of a Multi-Page App (MPA) but the power and capabilities of a Single-Page App (SPA). One of the big challenges of SPAs is network management resulting in a great deal of indirection and buggy code. This is especially noticeable in application state which Remix completely eliminates, but it's also an issue in individual components that communicate with a single-purpose backend endpoint (like a combobox search for example).
In this talk, Kent will demonstrate how Remix enables you to build complex UI components that are connected to a backend in the simplest and most powerful way you've ever seen. Leaving you time to chill with your family or whatever else you do for fun.
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
TypeScript and React are inseparable. What's the secret to their successful union? Quite a lot of surprisingly strange code. Learn why useRef always feels weird, how to wrangle generics in custom hooks, and how union types can transform your components.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
JavaScript in the browser runs many times faster than it did two decades ago. And that happened because the browser vendors spent that time working on intensive performance optimizations in their JavaScript engines.Because of this optimization work, JavaScript is now running in many places besides the browser. But there are still some environments where the JS engines can’t apply those optimizations in the right way to make things fast.We’re working to solve this, beginning a whole new wave of JavaScript optimization work. We’re improving JavaScript performance for entirely different environments, where different rules apply. And this is possible because of WebAssembly. In this talk, I'll explain how this all works and what's coming next.

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.
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.
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
React Day Berlin 2022React Day Berlin 2022
86 min
Using CodeMirror to Build a JavaScript Editor with Linting and AutoComplete
Top Content
WorkshopFree
Hussien Khayoon
Kahvi Patel
2 authors
Using a library might seem easy at first glance, but how do you choose the right library? How do you upgrade an existing one? And how do you wade through the documentation to find what you want?
In this workshop, we’ll discuss all these finer points while going through a general example of building a code editor using CodeMirror in React. All while sharing some of the nuances our team learned about using this library and some problems we encountered.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
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.
Testing Web Applications Using Cypress
TestJS Summit - January, 2021TestJS Summit - January, 2021
173 min
Testing Web Applications Using Cypress
WorkshopFree
Gleb Bahmutov
Gleb Bahmutov
This workshop will teach you the basics of writing useful end-to-end tests using Cypress Test Runner.
We will cover writing tests, covering every application feature, structuring tests, intercepting network requests, and setting up the backend data.
Anyone who knows JavaScript programming language and has NPM installed would be able to follow along.
Build a powerful DataGrid in few hours with Ag Grid
React Summit US 2023React Summit US 2023
96 min
Build a powerful DataGrid in few hours with Ag Grid
WorkshopFree
Mike Ryan
Mike Ryan
Does your React app need to efficiently display lots (and lots) of data in a grid? Do your users want to be able to search, sort, filter, and edit data? AG Grid is the best JavaScript grid in the world and is packed with features, highly performant, and extensible. In this workshop, you’ll learn how to get started with AG Grid, how we can enable sorting and filtering of data in the grid, cell rendering, and more. You will walk away from this free 3-hour workshop equipped with the knowledge for implementing AG Grid into your React application.
We all know that rolling our own grid solution is not easy, and let's be honest, is not something that we should be working on. We are focused on building a product and driving forward innovation. In this workshop, you'll see just how easy it is to get started with AG Grid.
Prerequisites: Basic React and JavaScript
Workshop level: Beginner