TypeScript Tricks You’ll Use All the Time in React

Destructuring with Types

You’ve probably used destructuring in JavaScript:

const user = { name: "Alice", age: 30 };
const { name } = user;

But in TypeScript, destructuring can be typed for extra safety:

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

const user: User = { name: "Alice", age: 30 };

const { name, age }: User = user; // Typed destructuring

console.log("name: ", name); // "name: Alice"
console.log("age: ", age); // "age: 30"

You can also destructure in function parameters:

function greet({ name }: { name: string }) {
  console.log(`Hi, ${name}`);
}

Even better, use interfaces to keep things clean:

interface GreetProps {
  name: string;
}

function greet({ name }: GreetProps) {
  console.log(`Hi, ${name}`);
}

✅ You will use this very often in React component props!

Spread Operator with Typed Objects

What is the Spread Operator?

The spread operator (...) is a feature in JavaScript (and supported in TypeScript) that allows you to “spread” the properties of an object or elements of an array into another object or array.

const user = { name: "Alice", age: 25 };
const updatedUser = { ...user, age: 26 };
  • ...user spreads all the properties of user into a new object.

  • We then override the age property.

This is especially useful when mutating objects immutably, i.e., creating a new object based on the old one but with some changes — a core concept in React state updates.

🧠 Use the spread operator instead of direct mutation to keep your data.

This helps React detect changes, triggers proper re-renders, and avoids unexpected side effects.

Let's say you want to update a specific property of the object. You will do the following:

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

const [user, setUser] = useState<User>({ name: "Alice", age: 25 });

setUser(prev => ({ ...prev, age: 26 })); // only update the age to 26 here.

Default Values with Destructuring

Destructuring + default values = cleaner, safer code.

function greet({ name = "Guest" }: { name?: string }) {
  console.log(`Hi, ${name}`);
}

greet({ name: undefined }); // "Hi, Guest"
greet({ name: "Bob" }); // "Hi, Bob"

Rename in Destructuring

You can rename variables while destructuring:

const user = { name: "Alice" };
const { name: userName } = user;

console.log(userName); // "Alice"

Typing Arrays and Spread

You can spread arrays too, and TypeScript keeps the types intact.

const todos: string[] = ["Buy milk"];
const updatedTodos = [...todos, "Walk dog"]; // Type is still string[]

Last updated