This Crazy Syntax Lets You Get An Array Element's Type
Learn how to extract the type of an array element in TypeScript using the powerful Array[number]
trick.
I've just learned about corepack
, a tool that bundles with Node.js and solves a bunch of problems with handling package managers. But I'll be using it in my development setup from now on.
corepack
is bundled with Node.js, and has been since Node.js 14.19. So, if you have Node.js, you have corepack
.
You can enable corepack
on your machine by running the following command:
corepack enable && corepack enable npm
This enables corepack
globally - you don't need to enable it per project.
corepack
makes sure you're using the correct package manager for your project. To configure the package manager for your project, add the packageManager
field to your package.json
:
{
// npm
"packageManager": "npm@10.8.1",
// pnpm
"packageManager": "pnpm@9.1.4",
// yarn
"packageManager": "yarn@3.1.1"
}
You must specify an exact version of the package manager you want to use - not a range. All of the below are not valid:
{
// not valid: uses a range
"packageManager": "npm@^10.8.1",
// not valid: specifies 'latest'
"packageManager": "pnpm@latest",
// not valid: must specify an exact version
"packageManager": "yarn"
}
Now, if you try to npm install
in a project that has packageManager
set to pnpm
, corepack
will show an error:
Usage Error: This project is configured to use pnpm
$ npm ...
And if you try to pnpm install
there, corepack
will automatically download and use the correct pnpm
version:
Corepack is about to download https://registry.npmjs.org/pnpm/-/pnpm-9.1.4.tgz.
Do you want to continue? [Y/n]
This ensures you're always using the correct package manager for your project.
corepack enable npm
?corepack
intercepts calls to pnpm
and yarn
to make sure you're using them correctly. This is set up by running corepack enable
.
Without running corepack enable npm
, you won't get the same validation when using npm
. So, we run corepack enable npm
to make sure that npm
gets treated the same way as pnpm
and yarn
.
I ran out of time to continue writing this article. Want me to keep going? What questions do you have? Let me know:
Share this article with your friends
Learn how to extract the type of an array element in TypeScript using the powerful Array[number]
trick.
Learn how to publish a package to npm with a complete setup including, TypeScript, Prettier, Vitest, GitHub Actions, and versioning with Changesets.
Enums in TypeScript can be confusing, with differences between numeric and string enums causing unexpected behaviors.
Is TypeScript just a linter? No, but yes.
It's a massive ship day. We're launching a free TypeScript book, new course, giveaway, price cut, and sale.
Learn why the order you specify object properties in TypeScript matters and how it can affect type inference in your functions.