Do Things Right with TypeScript

This is a collection of tricks and tribulations in TypeScript on node with npm.

A collection of pointers for the present and future.

Print the whole error

tsc --noErrorTruncation

Why tsconfig.json is hard

tsconfig.json is important, because the TS compiler does way more, way more flexibly, than the Java compiler does. It’s both a transpiler and a typechecker.

What kind of JS do you want outputted? Choose your level of ECMAScript compatibility (as ancient as ES3 or as modern as ESnext) and also your module system compatibility (commonjs, amd, or several more).

What will be magically be available in your runtime? Bring in the type declarations for these things (such as the DOM) with the `”lib”: [“DOM”]` compiler option, or in `”types”: [“@types/node”]` (node module globals like `__filename`, or node built-ins like `fs`).

Also choose how stringent the typechecking is, with “strict” and its various suboptions.

Choose where your input files are, and where your output files go.

Choose what to output: only JS? sourcemaps? type declarations? type declaration maps? … and for those maps, choose relative paths to the source.

The good news is: even if compilation has errors, tsc will output JS. So you can test even when tricky compile errors that you can’t figure out plague you.

Iterate through objects and arrays

There exists both for (const a in array) and a similar construct which shall not be named but contains the word in instead of of. Do not use that one.

To iterate through an array: for (const a of array) { … }

To iterate through an object: for (const key of Object.keys(obj)) {...}

Files to ignore

in .gitignore, we decide what does not go into source control. This includes:

  • compile output: *.js, *.d.ts, *
  • node_modules/

in .npmignore, we decide what does not go into the package on npm publish. npm publish. (caution: if you don’t have this file, it’ll use .gitignore, which is almost never what you want.) This includes:

  • node_modules/ (this one’s automatically not going in, but stick it here anyway)
  • tests: *.test.ts, tests/

If you’re like “why isn’t this file showing up? It is not in .npmignore!” then consider the files attribute in package.json. If that exists, you’ll get only those files.

Like what you read? Give Jessica Kerr a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.