Are the (module) types wrong?

Rate this content
Bookmark
GithubProject website
The video discusses the complexities of module systems in JavaScript, focusing on the disagreement between TypeScript and Node.js when importing the Helmet package. It highlights the differences between ESM and CommonJS, explaining how Node.js uses file extensions to determine the module format. The talk mentions the trace resolution flag in TypeScript, which helps in understanding module resolution. The Are the Types Wrong tool is introduced, which checks for discrepancies between TypeScript types and JavaScript files. The video also explores how declaration files in TypeScript are crucial for type checking and editor support. The CLI version of the tool makes it easier to integrate into publishing processes. The issues with module resolution stem from the rapid adoption of ESM syntax before TypeScript and Node.js caught up, leading to incorrect assumptions about the interoperation of the two formats.

From Author:

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

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

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 Transcription

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 next-generation build tool that leverages native ES modules for improved performance. It eliminates the need for bundling and improves hot module replacement. Vite provides an opinionated default configuration while still allowing advanced customization through plugins. It is framework agnostic and can be used for React and other applications. Vite is being adopted by Next.js and Create React App, and integration with Nuxt 3 offers significant speed improvements.
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
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
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
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
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.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
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.

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.
Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
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.