Skip to the solution
MediumFrontend15 min read

What does arethetypeswrong (attw) detect and how do you fix false ESM/CJS packages?

782 views

The problem

Question presented to candidate: "You publish a package that works for some users and breaks for others: ESM users get a type error on a default import that runs fine, CommonJS users get told to use a dynamic import. What does arethetypeswrong check, and how would you fix the package?"

What a strong answer should cover:

  • What attw does: packs the package and resolves every exports entrypoint the way TypeScript does under node10, node16 (from CJS and from ESM) and bundler, then compares the declaration file it finds with the JavaScript file Node would load
  • The core rule: under node16/nodenext a .d.ts file's module format comes from the nearest package.json "type" (.d.mts is always ESM, .d.cts always CJS), so one shared index.d.ts cannot describe both an .mjs and a .cjs file
  • The main problem kinds by name: Masquerading as CJS / as ESM, Incorrect default export (export default typed for module.exports =), CJS default export, Used fallback condition, Resolution failed / No types, Named exports
  • The fix: one declaration file per format (.d.mts next to .mjs, .d.cts next to .cjs), nested import / require conditions with "types" first in each, and export = for a CommonJS file that assigns module.exports
  • How it is used: attw --pack . (or --profile node16 / esm-only) in CI before publishing, because a wrong .d.ts is trusted by TypeScript and only fails for some consumers

Clarifying questions expected:

  • Does the package need to support CommonJS consumers at all, or can it be ESM-only?
  • Which module resolution settings do the consumers use (bundler, nodenext, old node10)?

Code / implementation expected: Optional โ€” a broken and a fixed package.json exports map, and why a default import type-checks wrongly.

  • publishing
  • arethetypeswrong

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 14 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptThe same CommonJS file, two different default imports
TypeScriptA toy attw: does the .d.ts format match the .js format?

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 32 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

How do you debug type-resolution and ESM/CJS mismatches with `traceResolution` and `explain`?

Continue