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.
...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.
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.