Level Up Your React: Adding Basic TypeScript for Stronger Components

Level Up Your React: Adding Basic TypeScript for Stronger Components

Learn how to use TypeScript for strings, arrays, objects, and common HTML elements in your React components

Building React applications often involves moving data and manipulating the DOM. JavaScript, while strong, is prone to type mistakes at runtime. TypeScript, a superset of JavaScript, comes to the rescue by ensuring type safety, resulting in more robust and manageable React code.

This blog post guides you through the basics of using TypeScript with React, focusing on:

  • Type Annotations for Strings, Arrays, and Objects

  • Typing Basic HTML Elements

  • Handling Form Events with TypeScript

Prerequisites:

  • Basic understanding of React and JSX.

  • Familiarity with TypeScript fundamentals (types, interfaces, etc.) is helpful but not mandatory.

Type Annotations for Strings, Arrays, and Objects

Let's start by adding type annotations to primitive data types:

// Without TypeScript
const name = "Lokesh";
const numbers = [1, 2, 3];
const person = { name: "Shrikrishna", age: 30 };

// With TypeScript
const name: string = "Lokesh";
const numbers: number[] = [1, 2, 3];
const person: { name: string; age: number } = { name: "Shrikrishna", age: 30 };

Here, we've explicitly declared the types of name, numbers, and person. TypeScript will now warn us if we attempt to assign incompatible values.

For arrays of objects, we can use nested types:

interface User {
  id: number;
  name: string;
}

const users: User[] = [
  { id: 1, name: "Shrikrishna" },
  { id: 2, name: "Lokesh" },
];

This defines an interface called User that specifies the properties and their types. We then use this interface to type the users array.

Typing Basic HTML Elements

Now, let's explore typing basic React components with HTML elements:

// Without TypeScript
function MyButton() {
  return <button>Click Me!</button>;
}

// With TypeScript
function MyButton(): JSX.Element {
  return <button>Click Me!</button>;
}

Here, we've added the type annotation JSX.Element to the MyButton function's return type. This indicates that the function returns a valid JSX element.

We can further refine the type based on the specific HTML element:

function MyButton(): React.ButtonHTMLAttributes<HTMLButtonElement> {
  return <button>Click Me!</button>;
}

This type extends the generic ButtonHTMLAttributes interface, providing access to properties like onClick, disabled, etc., for enhanced type safety specifically for button elements.

Handling Form Events with TypeScript

Forms are a crucial part of user interaction. Here's how to handle form events with TypeScript:

// Without TypeScript
function handleSubmit(event) {
  event.preventDefault();
  const name = event.target.name.value; // Can potentially be undefined
  console.log(name);
}

// With TypeScript
function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
  event.preventDefault();
  const formData = new FormData(event.currentTarget);
  const name = formData.get("name"); // Guaranteed to be a string
  console.log(name);
}

In the improved version, we define the handleSubmit function to accept a FormEvent<HTMLFormElement> argument. This type provides access to the form element and its methods, like preventDefault. We then use formData.get("name") to access the form data, ensuring type safety for the retrieved value.

Conclusion

Adding TypeScript to your React development workflow can significantly enhance code maintainability and catch potential errors early on. This blog post provided a basic introduction to using TypeScript for strings, arrays, objects, HTML elements, and form events in React components.