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.
Adding TypeScript to an existing React project can feel like a herculean task.
Let's break it down into a few simple steps.
You'll first need to install TypeScript as a dev dependency:
npm install --save-dev typescript
tsconfig.json
fileNext, you'll need to add a tsconfig.json
file to the root of your project. This file tells TypeScript how to compile your code.
I don't recommend using tsc --init
for this. It will generate a lot of unnecessary comments and hard-to-read defaults.
Instead, I recommend going to the tsconfig/bases repo to find a tsconfig.json
file that matches your project.
They have different tsconfig.json
files for different project types:
.ts
(or .tsx
)Next, you'll need to change a file to .ts
(or .tsx
if it contains a React component).
With the vast majority of modern projects, your framework of choice will be able to just work with the new .ts
file. This is because most bundlers (which frameworks use to compile your code) can handle both JavaScript and TypeScript.
If it doesn't head to that framework's TypeScript documentation to see what extra steps you need to take.
Now that you have TypeScript installed and a tsconfig.json
file, you can begin the migration.
If your project is anything larger than a few files, I recommend migrating one file at a time. This will help you avoid merge conflicts and make it easier to find bugs.
It'll also mean that any existing PRs don't need to be rewritten to include the TypeScript changes.
Your project might be in a stage where it has lots of JavaScript files AND lots of TypeScript files. This is fine as an intermediate step, and you should be able to keep shipping features while this change occurs.
I recommend Sentry's Migrating to TypeScript blog post for more information on how to do this.
Add TypeScript To An Existing React Project
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.