Having encountered a "oh my god" bug with JavaScript in a large React project, I spent all day just finding a typo error in props. From then on, I decided to completely switch to TypeScript. It's not as scary as you think! Implementing TypeScript with React built-in instructions correctly is the way to make your code safer, easier to maintain, and less buggy. I will show you why it is "true love", how to quickly set up projects with Vite and handle the most common things like props, state.
Why did I "swear" to never code React with vegetarian JavaScript again?
Combining TypeScript brings absolute peace of mind thanks to the ability to statically type, helping you detect errors right when typing code instead of waiting until running tests in the browser.
When I first started my career, I really liked the freedom of JavaScript. You can pass anything into a function without hindrance. But as the project ballooned, that freedom turned into a real nightmare. Why use TypeScript with React? Simply because it brings the discipline needed to manage complex data flows. At Pham Hai, we always set mandatory standards for using TS for all new projects. For those who want to change their lives, learning Learning TypeScript from scratch for JavaScript developers is an extremely important step to change programming thinking.
Catch errors in the bud: Say goodbye to the haunting "Cannot read properties of undefined".
TypeScript's static typing feature helps the compiler catch errors with incorrect data types, missing props, or incorrect variable names right during compilation.
Bạn đã bao giờ toát mồ hôi hột vì một lỗi runtime trên môi trường production chỉ vì một biến vô tình bị undefined chưa? Lợi ích của TypeScript trong React thể hiện rõ ràng nhất ở khả năng bắt lỗi sớm. Nhờ cơ chế định kiểu tĩnh khắt khe, trình biên dịch (Compiler) sẽ báo lỗi đỏ rực ngay trên màn hình khi bạn lỡ tay truyền một string vào một Component đang mong đợi number. Điều này đóng góp cực lớn vào việc nâng cao chất lượng mã và giúp bạn ngủ ngon hơn mỗi tối khi release tính năng mới.
Code "interprets" itself with IntelliSense: VS Code becomes the most powerful assistant.
IntelliSense in Visual Studio Code works perfectly with TypeScript, automatically suggesting the correct properties, methods, and data types for each component.
Khi bạn gõ props., một danh sách xổ xuống hiển thị chính xác những gì bạn có thể dùng. Đó là phép màu thực sự của IntelliSense trong Visual Studio Code. Bạn không cần phải mở lại file định nghĩa Component để xem nó cần nhận vào những thuộc tính gì nữa. Trải nghiệm phát triển được tối ưu hóa đến mức tối đa. Với những bạn đang trên con đường Học React JS từ đầu cho người mới, việc làm quen với sự hỗ trợ tận răng này sẽ giúp rút ngắn thời gian mò mẫm code đáng kể.
Confidently "refactor" without fear of collapsing the whole system.
Safe refactoring is one of TypeScript's greatest strengths, helping you rename variables or change data structures without worrying about missing any files that are using them.
During the life cycle of an application, data structure changes are inevitable. With pure JS, renaming a property in an object passed through the 5 Component layers is a minefield game. But with TS, you have safe refactoring at your fingertips. Compiler will review and point out every corner of the project that needs to be updated. The maintainability of the project thus increases to another level, making code handover or team work smoother than ever.
Start your React TypeScript project in a snap: Vite straight away!
Creating a React TypeScript project is now very simple and fast thanks to modern build tools like Vite, completely replacing old and slow boilerplates.
Installing React with TypeScript is no longer a tiring afternoon spent configuring Webpack. The community has developed great tools so you can code in seconds. Below is a picture of the project setup as of now in 2026.
Method 1 (Recommended): Speed up with Vite - Choice of 2026.
Using Vite to create React TypeScript projects helps server startup speed and Hot Module Replacement (HMR) many times faster than traditional tools.
Don't waste time on old tools, Vite is the current industry standard. Its build speed is so fast that before you can blink, the local server is already running. To initiate a React TypeScript project with Vite, simply open the terminal (make sure your device has Node.js installed) and type the following command:
npm create vite@latest my-react-app -- --template react-ts
Sau đó, di chuyển vào thư mục dự án, chạy npm install (hoặc dùng yarn) và khởi động với npm run dev. Quá trình này tạo ra một boilerplate cực kỳ gọn nhẹ, loại bỏ hoàn toàn các file rác không cần thiết. Đây chính là hướng dẫn cơ bản TypeScript React mà mình luôn nhấn mạnh khi training cho các bạn thực tập sinh.
Method 2 (For the nostalgic): Create React App (CRA) is fine.
Although no longer recommended as a preferred choice by the community, Create React App is still a popular way to set up projects with TypeScript templates for legacy systems.
Although most developers have migrated to Vite or Next.js, some legacy enterprise projects are still using Create React App. If you are in a situation where you must maintain or create new modules on this platform, the familiar initialization command will be:
npx create-react-app my-app --template typescript
However, as long-time professionals, we recommend that you avoid using CRA for any new projects from now on because the compilation speed is quite slow and it is no longer updated with the latest features on a regular basis.
Explore the tsconfig.json file: TypeScript's "brain" in the project.
The tsconfig.json file contains all the configuration that helps the compiler understand how to type check and output JavaScript code appropriate to the target runtime environment.
Ngay sau khi tạo dự án, bạn sẽ chú ý thấy một file tên là tsconfig.json nằm ở thư mục gốc. Đây chính là nơi bạn thiết lập "luật chơi" cho toàn bộ mã nguồn. Ví dụ, cờ strict: true là cấu hình bắt buộc phải bật để phát huy tối đa sức mạnh bắt lỗi của TS. Nó quy định mức độ khắt khe của trình biên dịch, cách xử lý các module và đường dẫn import. Lời khuyên của mình là đừng vội vàng copy paste cấu hình trên mạng hay xóa bừa nếu bạn chưa thực sự hiểu rõ tác dụng của từng dòng trong file này.
Typing in practice: From Props, State to Events
Mastering the styling of Props, State, and events is the most important step to mastering the development of safe, clean, and robust Components.
This is the core of the article TypeScript with React integration tutorial. We will stop talking about theory and go straight to practice how to use TypeScript with React in everyday coding tasks.
Props - "Contract" for Components: How to style props properly.
Styling props helps clearly define what data is allowed to be passed into the Component, completely preventing the transmission of incorrect types or missing required data.
Cách định kiểu props trong React TypeScript giống như việc bạn soạn thảo một bản hợp đồng cho Components của mình. Bạn khai báo rõ ràng Component này cần những nguyên liệu gì để hoạt động, và bất kỳ ai (kể cả chính bạn) khi gọi nó đều phải tuân thủ đúng "hợp đồng" đó.
type UserCardProps = {
name: string;
age: number;
avatarUrl?: string; // Dấu ? biểu thị đây là một prop không bắt buộc (optional)
};
const UserCard = ({ name, age, avatarUrl }: UserCardProps) => {
return (
<div>
<h3>{name}</h3>
<p>Tuổi: {age}</p>
{avatarUrl && <img src={avatarUrl} alt="Avatar" />}
</div>
);
};
Nhờ định nghĩa UserCardProps như trên, nếu đồng nghiệp của bạn truyền age="hai mươi" (dạng chuỗi), TypeScript sẽ lập tức gạch chân đỏ để cảnh báo trước khi code kịp chạy.
The never-ending battle: Should I use Type or Interface in React?
Both Type and Interface are used to define the shape of an object, but Interface is suitable for object-oriented extensions, while Type is strong in data type operations.
When learning TypeScript for React beginners, the classic question that always comes up is: Use Type or Interface? In fact, comparing Type and Interface in TypeScript React shows that they solve 90% of the same needs.
| Criteria | Interface | Type |
|---|---|---|
| Mở rộng (Extends) | Very good, OOP-like syntax | Có thể, dùng Intersection (&) |
| Kiểu phức tạp | No direct support | Hỗ trợ Union (|), Tuple |
| Khuyên dùng trong React | Define the Props/State structure | Define logical data types |
Tại team mình, mọi người thường quy ước: Dùng Interface cho Props của Component vì tính kế thừa dễ đọc, và dùng Type cho các kiểu dữ liệu phức tạp như Union Type (type Status = 'loading' | 'success' | 'error') hoặc Intersection Type. Nếu bạn muốn đào sâu hơn về cơ chế hoạt động, bài viết Interface vs Type TypeScript khác nhau thế nào sẽ giải đáp cặn kẽ mọi thắc mắc của bạn.
State management is safe with the useState Hook and explicit styling.
TypeScript can infer the type for useState itself with simple initialization values, but you need to explicitly type using Generics for complex objects or arrays.
With simple values such as numbers or boolean strings, TS is smart enough to understand itself (Type Inference). But with more complex data, typing state with useState in React TypeScript requires you to use Generics syntax.
// Khai báo state có thể chứa object User hoặc mang giá trị null khi chưa fetch được data
const [currentUser, setCurrentUser] = useState<UserCardProps | null>(null);
Cách viết <UserCardProps | null> báo cho React biết State này có thể thay đổi linh hoạt giữa hai trạng thái. Nếu bạn còn lơ mơ về cách hoạt động của các hàm này, đừng bỏ qua việc đọc React Hooks useState useEffect hướng dẫn và đồng thời tìm hiểu thêm TypeScript Generics giải thích dễ hiểu có ví dụ để nắm chắc nền tảng tư duy.
Handle onClick, onChange events without fiddling with data types.
React provides built-in data types for events such as React.MouseEvent or React.ChangeEvent, making getting values from the DOM absolutely accurate and safe.
Khi làm việc với form, việc lấy e.target.value rất hay bị lỗi lặt vặt nếu không có TS bảo vệ. Rất may, React đã cung cấp sẵn các type tuyệt vời cho Hooks và Events. Ví dụ, cho một ô input, bạn sẽ viết: const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {...}. Đối với một nút bấm: React.MouseEvent<HTMLButtonElement>. Bạn không cần phải học thuộc lòng chúng, cứ trỏ chuột vào thuộc tính onChange hoặc onClick trong thẻ JSX, VS Code sẽ gợi ý kiểu sự kiện chuẩn xác cho bạn copy.
"TypeScripting" an existing React project: Is it as difficult as rumored?
Converting a running project from JavaScript to TypeScript can be done gradually, file by file, without interrupting the development of new features.
If you're maintaining an old project, integrating TypeScript into an existing React project may sound as risky as changing an airplane engine mid-flight. But actually, the Node.js ecosystem supports this extremely smoothly.
Steps to prepare and install TypeScript into an existing JavaScript project.
Start by installing the necessary dependencies like typescript, @types/react, @types/react-dom via npm and create a compatible tsconfig.json configuration file.
Đầu tiên, bạn cần cài đặt các thư viện lõi. Mở terminal và chạy lệnh:
npm install --save-dev typescript @types/node @types/react @types/react-dom
Sau đó, chạy npx tsc --init để sinh ra file cấu hình. Ở bước này, một mẹo nhỏ sống còn là hãy nhớ bật cờ allowJs: true trong file config. Điều này cho phép các file .js cũ và .tsx mới có thể chung sống hòa bình trong cùng một codebase, giúp dự án vẫn build thành công trong quá trình bạn migrate.
Step-by-step conversion strategy: From .js to .tsx file and handle "any" errors.
Change the extension of Component files from low to high (from small UI Components to large Pages), prioritize the definition of shared data types such as Enums and minimize the abuse of "any" type.
Chuyển từ JavaScript sang TypeScript trong React không phải là việc bạn có thể làm xong trong một đêm đối với dự án lớn. Hãy áp dụng chiến lược "vết dầu loang". Bắt đầu từ những "leaf components" (những component nhỏ nhất ở cuối cây DOM không chứa component con nào khác như Button, Input, Label). Đổi đuôi .js thành .tsx.
Ban đầu, bạn có thể phải "ăn gian" dùng kiểu any để ép các lỗi đỏ phải im lặng, nhưng hãy đặt mục tiêu gỡ bỏ dần chúng qua từng sprint. Việc kết hợp thêm các công cụ quản lý state hiện đại như Redux Toolkit (vốn được sinh ra để hỗ trợ TS cực tốt) hoặc sử dụng Enums để quản lý các hằng số cấu hình sẽ làm dự án của bạn cứng cáp và chuyên nghiệp hơn hẳn.
Switching to TypeScript can feel a bit cumbersome at first because you have to type more code and think about data structures more. But believe me, it is an extremely worthy investment for your "peace" and the long-term quality of the project. It helps you write better code, be more confident when refactoring, and work more easily in teams. Don't worry too much about memorizing every advanced concept at once. Just start integrating TypeScript with React integration guide from the smallest components, you will quickly feel the great difference it brings.
Are you ready to "upgrade" your React project to make the code smoother and less buggy? Try creating a small project with Vite and TypeScript today to experiment. If you encounter any initial difficulties in the styling or config section, please leave a comment below and I will directly assist you!
Lưu ý: Thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.