Add TypeScript To An Existing React Project
Learn how to add TypeScript to your existing React project in a few simple steps.
TypeScript 5.0 has made it to Total TypeScript!
It brought a lot of improvements - you can learn all about it in our 5.0 breakdown.
The most exciting feature for Total TypeScript was const type parameters.
It lets you specify a type parameter as const
- meaning that everything that gets passed to that parameter gets inferred as if it were as const
.
typescript
const routes = <const TRoutes>( routes: TRoutes ) => { return routes; }; const myRoutes = routes({ user: "/user", createUser: "/user/create", }); Object.values(myRoutes); // ['/user', '/user/create'] // Before 5.0, myRoutes would be inferred as string[]
Before 5.0, you needed to use a hack in TypeScript to get this behaviour - the F.Narrow type helper from ts-toolbelt
. I even taught this in Total TypeScript!
No longer - I've re-recorded 3 exercises in TT's Advanced Patterns workshop to take advantage of const type annotations.
I can't wait to see what you build with them!
Share this article with your friends
Learn how to add TypeScript to your existing React project in a few simple steps.
Learn the essential TypeScript configuration options and create a concise tsconfig.json file for your projects with this helpful cheatsheet.
Big projects like Svelte and Drizzle are not abandoning TypeScript, despite some recent claims.
Learn different ways to pass a component as a prop in React: passing JSX, using React.ComponentType, and using React.ElementType.
Learn about TypeScript performance and how it affects code type-checking speed, autocomplete, and build times in your editor.
When typing React props in a TypeScript app, using interfaces is recommended, especially when dealing with complex intersections of props.