Extracts the return type of a function.
type FunctionReturn = ReturnType<typeof functionName>;
function getUser() {
return {
id: 1,
name: "Alice",
email: "alice@example.com"
};
}
*// Extract return type automatically*
type User = ReturnType<typeof getUser>;
*// User is { id: number; name: string; email: string; }// Use the extracted type*
const user: User = {
id: 2,
name: "Bob",
email: "bob@example.com"
};
function fetchConfig() {
return {
apiUrl: "<https://api.example.com>",
timeout: 5000,
retries: 3,
features: {
darkMode: true,
notifications: {
email: true,
push: false
}
}
};
}
*// Avoid manually typing this complex structure*
type AppConfig = ReturnType<typeof fetchConfig>;
*// Now use it anywhere*
function loadConfig(): AppConfig {
return fetchConfig();
}
function createArray<T>(items: T[]) {
return items;
}
type StringArray = ReturnType<typeof createArray<string>>;
*// StringArray is string[]*
typeof functionName to get the function type first.Promise<T>).