capypad
0 day streak
typescript / intermediate
Snippet

Extracting Types with ReturnType

The ReturnType utility type extracts the return type of a function. This ensures that if the function's implementation changes, the dependent types update automatically, maintaining a single source of truth.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
function fetchData() {
return { id: 1, name: "Alice", active: true };
}
 
type UserProfile = ReturnType<typeof fetchData>;
 
const user: UserProfile = {
id: 2,
name: "Bob",
active: false
};
Breakdown
1
type UserProfile = ReturnType<typeof fetchData>;
Uses 'typeof' to get the function signature and 'ReturnType' to isolate what it returns.