All Posts
Jan 2, 2025

Typescript with React

A brief introduction of Typescript with React

Featured image for Typescript with React

Why use Typescript?

1. Type Safety

  • TypeScript provides static type checking, which helps catch errors during development rather than at runtime.
  • Ensures that props, state, and component return values have the correct types, reducing bugs. Example - Type-checking ensures you pass the correct props to a component.

Type Safety

2. Enhanced Developer Experience

  • IDEs like VS Code provide better autocompletion and context-aware suggestions when using TypeScript.
  • TypeScript flags issues in your code as you write it, reducing the need for extensive debugging.

Developer Experience

3. Improved Refactoring

  • Typescript makes it easier to refactor code safely.
  • For example, if you rename a prop or variable, TypeScript ensures you update all its references across your project.

TypeScript is not a completely different language. Instead, it is a superset of JavaScript. This means that any valid JavaScript code is also valid TypeScript code. Because of this compatibility, migrating from JavaScript to TypeScript is straightforward and incremental. You can start with your existing JavaScript code and gradually introduce TypeScript features as needed.

Typescript Basics

Types

  • Types define the kind of value a variable can hold. They help catch errors by ensuring variables only hold the expected type of data.
  • Example of Basic Types:
let count: number = 5; // Number
let name: string = "React" // String
let isActive: boolean = true; // Boolean
let items: string[] = ["one", "two"] // Array of Strings
let user: { id: number, name: string } = { id: 1, name: "John" } // An object with different properties

Interfaces

  • Interfaces are used to define the structure of objects. They make your code cleaner and reusable especially when multiple objects share the same structure.
  • Example - Defining an Object with an Interface
interface User {
id: number,
name: string
}
let user: User = { id: 1, name: "Jane" } // Matches the structure defined by the interface

If you try to add an extra property (e.g., age) or miss a required one (id or name), TypeScript will alert you.

Extending Interfaces

  • Interfaces can also extend others making them versatile for complex scenarios.
interface User {
id: number,
name: string
}
interface Admin extends User {
role: string
}
let admin: Admin = { id: 1, name: "Alice", role: "Moderator" };

Annotations in Functions

  • Annotations in functions define the types of inputs (parameters) and outputs (return value). This makes functions predictable and helps catch errors.
const add = (a: number, b: number): number => {
return a + b;
}
console.log(add(2, 3)); // Works fine
console.log(add("2", 3)) // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
  • In the function above:
    • a: number and b: number specify the expected types of parameters.
    • : number after the parameters specifies the return type.
const greet = (user: { id: number, name: string}): string => {
return `Hello ${user.name}`
}
console.log(greet({ id: 1, name: "John" })); // Outputs: Hello John

Key Benefits

  • Types ensure each variable holds the correct data.
  • Interfaces standardize object structures, making your code cleaner and more maintainable.- Annotations provide clarity in functions, making them more predictable and reliable.

Using Typescript with React

Setup a React boilerplate project with Typescript template. We will use Vite for our project setup.

React Typescript boilerplate setup using Vite

  1. Open your terminal.
  2. Run the following command to setup a boilerplate React project with Typescript:
npm create vite@latest my-react-app -- --template react-ts
  1. Install the dependencies using npm install.
  2. Run the development server using this command npm run dev.

Note that all the React components and files in a typescript environment end with .tsx extension.

Convert a React component to use Typescript

Create a simple React component called Greet and use it in App

/components/Greet.tsx

const Greet = () => {
return (
<div>
<h2>Welcome User! You have 10 unread messages.</h2>
</div>
)
}
export default Greet

App.tsx

import Greet from './components/Greet'
function App() {
return (
<div>
<Greet />
</div>
)
}
export default App

In the example above we use the Greet component and render it in App component. Notice that the data is hardcoded in the Greet component, and we are not using any props.

Add a prop called name to the Greet component

Now let's introduce a prop called name and pass it to the Greet component.

App.tsx

import Greet from './components/Greet'
function App() {
return (
<div>
<Greet name="John" />
</div>
)
}
export default App

/components/Greet.tsx

const Greet = (props) => {
return (
<div>
<h2>Welcome {props.name}! You have 10 unread messages.</h2>
</div>
)
}
export default Greet

Notice after making these changes, we will start getting the following warning message in VS Code when we hover over the props in Greet component.

Parameter 'props' implicitly has an 'any' type.ts(7006)

  • This warning occurs because we have not defined the type for the props object in the Greet component. TypeScript is asking us to specify the expected shape of the props.

Define the String Prop Types using Typescript

To fix the warning, we can define the type for the props object. There are two common ways to define prop types in TypeScript: using Type Aliases or Interfaces.

1. Using a Type Alias

/components/Greet.tsx

type GreetProps = {
name: string
}
const Greet = (props: GreetProps) => {
return (
<div>
<h2>Welcome {props.name}! You have 10 unread messages.</h2>
</div>
)
}
export default Greet

2. Using an Interface

/components/Greet.tsx

interface GreetProps = {
name: string
}
const Greet = (props: GreetProps) => {
return (
<div>
<h2>Welcome {props.name}! You have 10 unread messages.</h2>
</div>
)
}
export default Greet

Both approaches achieve the same result. It’s a matter of preference whether you use a type alias or an interface for defining props.

Passing Number Props

Let's extend the Greet component to accept more props. For example - we can add a prop called messageCount to display the number of unread messages.

/components/Greet.tsx

type GreetProps = {
name: string;
messageCount: number;
}
const Greet = (props: GreetProps) => {
return (
<div>
<h2>Welcome {props.name}! You have {props.messageCount} unread messages.</h2>
</div>
)
}
export default Greet

App.tsx

import Greet from './components/Greet'
function App() {
return (
<div>
<Greet name="John" messageCount={5} />
</div>
)
}
export default App

Passing a Boolean Prop

Let's also pass a boolean prop called isLoggedIn to the Greet component.

If the value of isLoggedIn is true, we will display user's name and message. And if it's false, we will display a generic message "Welcome Guest".

/components/Greet.tsx

type GreetProps = {
name: string;
messageCount: number;
isLoggedIn: boolean
}
const Greet = (props: GreetProps) => {
return (
<div>
<h2>{props.isLoggedIn ? `Welcome ${props.name}! You have ${props.messageCount} unread messages.` : 'Welcome Guest'}</h2>
</div>
)
}
export default Greet

App.tsx

import Greet from './components/Greet'
function App() {
return (
<div>
<Greet name="John" messageCount={5} isLoggedIn={false} />
</div>
)
}
export default App

Passing Object Props

Let's create a new component called Person and use it in the App.

App.tsx

import Greet from './components/Greet'
import Person from './components/Person'
const personName = {
first: 'Bruce',
last: 'Wayne'
}
function App() {
return (
<div>
<Greet name="John" messageCount={5} isLoggedIn={false} />
<Person name={personName} />
</div>
)
}
export default App

/components/Person.tsx

type PersonProps = {
name: {
first: string;
last: string;
}
}
const Person = (props: PersonProps) => {
return (
<div>{props.name.first} {props.name.last}</div>
)
}
export default Person

Now this type declaration in the component above can be further expanded to look like this:

type FullName = {
first: string;
last: string;
}
type PersonProps = {
name: FullName;
}
const Person = (props: PersonProps) => {
return (
<div>{props.name.first} {props.name.last}</div>
)
}
export default Person

Explanation:

  • The type FullName defines the structure of the name object.
  • The Person component receives a single name prop typed as FullName.
  • This ensures that only objects matching the FullName type can be passed as props.

Passing an Array of Objects

Let's create a TodoList component and use it in the App component.

App.tsx

import TodoList from './components/TodoList'
const todos = [
{ id: 1, title: "Learn TypeScript", completed: true },
{ id: 2, title: "Build a React App", completed: false },
{ id: 3, title: "Deploy to Production", completed: false }
]
function App() {
return (
<div>
<TodoList todos={todos} />
</div>
)
}
export default App

/components/TodoList.tsx

type Todo = {
id: number,
title: string,
completed: boolean
}
type TodoListProps = {
todos: Todo[]
}
const TodoList = (props: todoListProps) => {
return (
<div>
{props.todos.map((todo) => {
return (
<div key={todo.id}>
<input type="checkbox" defaultChecked={todo.completed} />
{todo.title}
</div>
)
})}
</div>
)
}
export default TodoList

Explanation

  • The Todo type defines the structure of each item in the todos array.
  • TodoList component expects a single todos prop of type Todo[] (an array of todo objects).
  • Typescript ensures that all the objects in the array adhere to the Todo type.

Handling Multiple Prop Types in TypeScript using the Union operator

In TypeScript, you can define a React component that receives a prop with multiple possible types using the | (union) operator. This allows a prop to accept different types while still benefiting from TypeScript's type checking.

Let's create a button component that supports different styles based on the variant prop. The variant prop can be one of several predefined string values: "primary", "secondary", "danger", "success", and "warning".

/components/Button.tsx

type ButtonProps = {
label: string;
variant: "primary" | "secondary" | "danger" | "success" | "warning";
}
const Button = (props: ButtonProps) => {
const getVariantClasses = (variant: ButtonProps["variant"]) => {
switch (variant) {
case "primary":
return "bg-blue-500 text-white hover:bg-blue-600";
case "secondary":
return "bg-gray-500 text-white hover:bg-gray-600";
case "danger":
return "bg-red-500 text-white hover:bg-red-600";
case "success":
return "bg-green-500 text-white hover:bg-green-600";
case "warning":
return "bg-yellow-500 text-black hover:bg-yellow-600";
default:
return "";
}
};
return (
<button className={getVariantClasses(props.variant)}>{props.label}</button>
)
}
export default Button

We can now use this component in our App.js file like this:

App.tsx

<Button variant="primary" label="Submit" />
<Button variant="secondary" label="Cancel" />
<Button variant="danger" label="Delete" />
<Button variant="success" label="Confirm" />
<Button variant="warning" label="Caution" />

Explanation

  • Using Union Types: The variant prop is strictly typed to accept only specific string values ("primary" | "secondary" | "danger" | "success" | "warning"). This prevents accidental errors when using the component.
  • TypeScript ensures that only valid variants are used, reducing bugs and improving maintainability.

Understanding the children Prop in React with TypeScript

In React, components can receive other components or elements as children. This allows for reusable, composable UI structures.

In TypeScript, we use the React.ReactNode type for the children prop.

What is React.ReactNode?

React.ReactNode is a TypeScript type that represents anything that can be rendered in React, such as:

  • JSX elements (<div>...</div>)
  • Strings ("Hello")
  • Numbers (42)
  • Fragments (<>...</>)
  • Components (<MyComponent />)
  • null or undefined

Example 1: A simple wrapper component

Here's a basic example of a Card component that accepts children.

type CardProps = {
children: React.ReactNode;
}
const Card = (props: CardProps) => {
return (
<div>{props.children}</div>
)
}
export default Card

Usage:

<Card>
<h2>This is a Card</h2>
<p>It can contain any content inside it.</p>
</Card>

Example 2: Passing a component as Children

We can also pass a separate component as a child

// Defining a component
const Message = () => {
return (
<p>This is a message in a card</p>
)
}
// Usage with the Card component
<Card>
<Message />
</Card>

Understanding the types React.ReactNode and React.ReactElement

In the above section we learned about children props. We also learned that usually React.ReactNode is the typescript type that can be assigned to children prop.

What is React.ReactNode?

React.ReactNode represents anything that can be rendered in React, including:

  • JSX elements (<div>...</div>)
  • Strings ("Hello")
  • Numbers (42)
  • Fragments (<>...</>)
  • Components (<MyComponent />)
  • null or undefined

When to Use React.ReactNode?

Use React.ReactNode when you want to allow any valid React content as children.

Example: A Wrapper component accepting any content

type WrapperProps = {
children: React.ReactNode;
}
const Wrapper = (props: WrapperProps) => {
return (
<div>
{props.children}
</div>
)
}

Usage:

<Wrapper>
<h1>Title</h1>
<p>This is a paragraph.</p>
Text is also allowed.
{42} {/* Numbers work too */}
</Wrapper>

✅ Why? Because React.ReactNode accepts anything React can render.


What is React.ReactElement?

React.ReactElement represents a specific React element created using JSX or React.createElement().

  • It is always a single element.
  • It must be a valid React component.
  • It does not allow plain text, numbers, or null.

When to Use React.ReactElement?

Use React.ReactElement when you need to enforce that children must be a single valid React element (not text or multiple elements).

Example: A component expecting a single child component

type CardProps = {
children: React.ReactElement // Only allows a single React element
}
const Card = (props: CardProps) => {
return (
<div>
{props.children}
</div>
)
}

Usage

✅ Valid: A single component is passed

<Card>
<h2>Single Child</h2>
</Card>

❌ Invalid: Multiple children or text

<Card>
<h2>Single Child</h2>
<p>Multiple elements are not allowed.</p>
</Card>

✅ Fix: Wrap multiple elements in a single div

<Card>
<div>
<h2>Single Child</h2>
<p>Multiple elements are not allowed.</p>
</div>
</Card>

Key Differences

FeatureReact.ReactNodeReact.ReactElement
Accepts text ("Hello")✅ Yes❌ No
Accepts numbers (42)✅ Yes❌ No
Accepts fragments (<>...</>)✅ Yes❌ No
Accepts null or undefined✅ Yes❌ No
Accepts multiple children✅ Yes❌ No
Ensures it's a valid React component❌ No✅ Yes

Making Props Optional in TypeScript

In TypeScript, we can define optional props in a React component by using the ? operator. This ensures that the prop can be omitted when using the component.

Why Use Optional Props?

  • Flexibility: The component works even if certain props are not provided.
  • Better Defaults: You can assign default values when a prop is missing.

Example: A Button Component with Optional Props

type ButtonProps = {
variant: "primary" | "secondary";
label: string;
disabled?: boolean; // Optional prop
onClick?: () => void; // Optional prop
}
const Button = (props: ButtonProps) => {
const { variant, label, onClick, disabled = false } = props
return (
<button
className={`px-4 py-2 rounded ${variant === "primary" ? "bg-blue-500 text-white" : "bg-gray-500 text-black"}`}
disabled={disabled}
onClick={onClick}
>
{label}
</button>
)
}

Usage:

With all props

<Button variant="primary" label="Click Me" disabled onClick={() => alert("Clicked!")} />

Witout optional props

<Button variant="secondary" label="Submit" /> {/* Works fine without disabled or onClick */}

Event Props in Typescript

In React with TypeScript, event props are the properties passed to components that are used to handle various user interactions, such as clicks, changes in form fields, key presses, and other events.

For the two most common event types — the click event and the onChange event — TypeScript allows us to define the event types to provide better type safety and autocompletion.

Click event (onClick)

In React, a click event is triggered when an element (like a button, div, etc.) is clicked. In TypeScript, the type of the event is usually specified as React.MouseEvent.

Example

Button.ts

type ButtonProps = {
handleClick: (event: React.MouseEvent<HTMLButtonElement>) => void
}
const Button = (props) => {
return (
<button onClick={props.handleClick}>Click Me</button>
)
}
export default Button

Usage

App.ts

<Button handleClick={(event) => {
console.log("Button clicked", event)
}} />

Explanation:

  • React.MouseEvent is the type for mouse events, including click.
  • The HTMLButtonElement generic type tells TypeScript that the event is coming from a button element, so it provides proper typings for the target element (like event.target.value or other properties).
  • If you add a click event to a div, h2, or any other HTML element, you should update the generic type accordingly. Instead of HTMLButtonElement, you would use the corresponding type for that element, such as HTMLDivElement or HTMLHeadingElement.

Example with a div

const handleDivClick = (event: React.MouseEvent<HTMLDivElement>) => {
console.log('Div clicked!', event.target);
};
return <div onClick={handleDivClick}>Click Me</div>;

General Rule

Use the correct generic type based on the element:

  • React.MouseEvent<HTMLButtonElement> - for <button>
  • React.MouseEvent<HTMLDivElement> - for <div>
  • React.MouseEvent<HTMLHeadingElement> - for <h1>, <h2> etc
  • React.MouseEvent<HTMLElement> - for a more generic approach if element type may vary.

onChange event (onChange)

The onChange events in React is used for handling changes to form elements such as text inputs or select dropdowns. The event type for onChange is typically React.ChangeEvent in TypeScript.

Example

Input.tsx

type InputProps = {
value: string;
handleChange: (event: React.ChangeEvent<HTMLInputElement>) => void
}
const Input = (props: InputProps) => {
return (
<input type='text' value={props.value} onChange={props.handleChange} />
)
}
export default Input

Usage

App.tsx

function App() {
return (
<div>
<Input value="" handleChange={(event) => console.log(event)} />
</div>
)
}
export default App

In the example above we see the handleChange function being passed as a prop to the component from the parent level. But this same typing also holds good if we are defining the handleChange function within the component.

const Input = () => {
const [value, setValue] = useState('');
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
console.log(event)
setValue(event.target.value);
}
return (
<input type="text" value={value} onChange={handleChange} />
)
}
  • React.ChangeEvent is used for change events like text input changes.
  • The HTMLInputElement type is specified for input elements, so event.target will be typed accordingly (in this case, it's an HTMLInputElement, and you can access properties like value, checked, etc.).

Style props in TypeScript - React.CSSProperties

In TypeScript the style prop in React is typically typed as React.CSSProperties. This type ensures that the style object adheres to the CSS rules and provides autocompletion for valid CSS properties.

Example

Here's an example of how to type the style prop in a React component:

// Box.tsx
type BoxProps = {
style?: React.CSSProperties
}
const Box = (props: BoxProps) => {
return (
<div style={props.style}>Styled Box</div>
)
}
export default Box
// Usage in App.tsx
const App = () => {
return (
<Box style={{ backgroundColor: 'lightblue', padding: '20px', borderRadius: '10px' }} />
)
}
export default App

Explanation:

  • We define BoxProps with a style prop of type React.CSSProperties.
  • The style prop is optional (style?)
  • In the Box component we apply the style prop to the div.
  • When using the Box component, we pass a valid inline style object.

Why Use React.CSSProperties?

  • ✅ Autocompletion & Type Safety: TypeScript suggests valid CSS properties and values.
  • ✅ Prevents Errors: If you use an invalid property, TypeScript throws an error.
  • ✅ Automatic Unit Inference: For numeric properties like width, height, or margin, TypeScript allows numbers (10) instead of requiring strings ("10px").
const style: React.CSSProperties = {
width: 100, ✅ Correct (assumed as '100px')
height: "50px", ✅ Correct
color: "red", ✅ Correct
fontWeight: "bold", ✅ Correct
invalidProperty: "test" ❌ Error: Property does not exist in 'CSSProperties'
}

TypeScript assumes pixels (px) when a numeric value is assigned to a property like width, height, margin, etc. But if you want to specify a different unit (e.g., em, rem, vw, %), you must use a string instead of a number.

Destructuring Props in TypeScript

In the previous examples, we used props directly in the function parameter and accessed them using props.propName. However, destructuring props inside the function definition can make the code cleaner and more readable.

In this section, we'll explore how to destructure props directly in the function parameter with simple examples, including handling optional props and default values.

Basic Example: Heading Component

type HeadingProps = {
text: string;
}
const Heading = (props: HeadingProps) => {
return (
<h1>{props.text}</h1>
)
}
export default Heading
  • The code above creates a very simple Heading component that receives a text prop. This is the pattern we are already familiar with.
  • In the function above, we can replace props on line #5 with { text }
  • We can simply destructure the props in the function parameter and access the prop name directly instead of using props.propname.

Example 1: Heading Component after destructuring props

type HeadingProps = {
text: string;
}
const Heading = ({ text }: HeadingProps) => {
return (
<h1>{text}</h1>
)
}
export default Heading

Example 2: Example with Default Props

type ParagraphProps = {
content: string;
color: string;
}
const Paragraph = ({ content, color = 'black'}: ParagraphProps) => {
return (
<p style={{ color }}>{content}</p>
)
}
// Usage
<Paragraph content="This is a paragraph" />;
<Paragraph content="Colored text" color="blue" />;

In this example Default value (black) for color is assigned directly in the function parameter.

Example 3: Button with an Event Handler

type ButtonProps = {
label: string;
onClick: () => void;
}
const Button = ({label, onClick}: ButtonProps) => {
return (
<button onClick={onClick}>{label}</button>
)
}
// Usage
<Button label="Click Me" onClick={() => alert("Button clicked!")} />;

Example 4: Card component with multiple props.

type CardProps = {
title: string;
description: string;
imageUrl: string;
}
const Card = ({ title, description, imageUrl }: CardProps) => {
return (
<div className="border p-4 rounded shadow">
<img src={imageUrl} alt={title} className="w-full h-40 object-cover" />
<h2 className="text-xl font-bold">{title}</h2>
<p>{description}</p>
</div>
)
}
// Usage
<Card
title="Beautiful Sunset"
description="A stunning view of the sunset over the mountains."
imageUrl="https://via.placeholder.com/300"
/>;

Key Takeaways

  • Destructure props directly in the function parameter whenever possible.
  • Use default values in the function parameter for optional props.