Destructuring is a convenient way to extract values from objects and arrays into separate variables. TypeScript adds type safety to this JavaScript feature.
Object Destructuring
Extract properties from objects into variables:
const person = {
name: 'Tony',
age: 45,
key: 'IronMan',
};
const { name, age, key } = person;
console.log({ name, age, key });
// { name: 'Tony', age: 45, key: 'IronMan' }
Renaming Variables
Use the colon : to rename variables during destructuring:
const { name: ironmanName, age, key } = person;
console.log({ ironmanName, age, key });
// { ironmanName: 'Tony', age: 45, key: 'IronMan' }
The syntax name: ironmanName means “take the name property and assign it to a variable called ironmanName”.
Destructuring Function Parameters
Destructure objects directly in function parameters:
interface Hero {
name: string;
age: number;
key: string;
rank?: string;
}
const useContext = ({ key, name, rank, age }: Hero) => {
return {
keyName: key,
user: {
name: name,
age: age,
},
rank: rank
};
};
Destructuring in function parameters makes it clear exactly which properties your function needs.
Nested Destructuring
Extract values from nested objects:
const { rank, keyName, user: { name } } = useContext(person);
console.log({ rank, keyName, name });
// { rank: undefined, keyName: 'IronMan', name: 'Tony' }
Array Destructuring
Extract values from arrays based on position:
const characterNames = ['goku', 'vegeta', 'trunks'];
const [, , p3] = characterNames;
console.log(p3); // "trunks"
Commas without variable names skip elements. In the example above, we skip the first two elements and only extract the third.
Destructuring Function Returns
Destructure values returned from functions:
const returnsArrayFn = () => {
return ['ABC', 123] as const;
};
const [letras, numeros] = returnsArrayFn();
console.log(letras, numeros); // "ABC" 123
The as const Assertion
The as const assertion creates a readonly tuple type:
// Without 'as const': returns (string | number)[]
// With 'as const': returns readonly ['ABC', 123]
const returnsArrayFn = () => {
return ['ABC', 123] as const;
};
Without as const, TypeScript treats the array as (string | number)[], losing information about the specific types at each position.
Common Use Cases
React Hooks
Destructuring is commonly used with React hooks:
const [state, setState] = useState(0);
const [text, setText] = useState('');
API Responses
Extract specific fields from API responses:
const { data, error, loading } = await fetchUser();
Configuration Objects
Destructure configuration in function parameters:
const createServer = ({ port, host, ssl }: ServerConfig) => {
// Use port, host, ssl directly
};
Best Practices
- Use meaningful names: When renaming, choose clear variable names
- Don’t over-nest: Deeply nested destructuring can be hard to read
- Destructure early: Extract values at the start of functions
- Use with interfaces: Combine destructuring with TypeScript interfaces for type safety