Add TypeScript To An Existing React Project
Learn how to add TypeScript to your existing React project in a few simple steps.
In TypeScript, if you try to assign to a property of a possibly undefined object, you'll get an error:
'X' is possibly undefined.
ts
obj .foo = "bar";
You might think that you can use the optional chaining syntax to fix this:
ts
obj ?.foo = "bar";
But you end up with an error:
The left-hand side of an assignment expression may not be an optional property access.
This is because optional chaining is only for reading properties (or deleting properties), not for assigning to them.
But today, the optional chaining for assignments proposal has landed in Stage 1 of TC39.
If this proposal gets adopted into JavaScript, the code below will no longer error.
ts
obj ?.foo = "bar";
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.