prettier-plugin-explicit-return
v0.0.2
Published
A Prettier plugin that automatically adds explicit return type annotations to TypeScript functions using type inference
Maintainers
Readme
Prettier Plugin Explicit Return
A Prettier plugin that automatically adds explicit return type annotations to TypeScript functions using type inference.
Installation
npm install --save-dev prettier-plugin-explicit-returnUsage
Add the plugin to your Prettier configuration:
.prettierrc.json:
{
"plugins": ["prettier-plugin-explicit-return"]
}package.json:
{
"prettier": {
"plugins": ["prettier-plugin-explicit-return"]
}
}Then format your TypeScript files as usual:
npx prettier --write "**/*.{ts,tsx}"Features
This plugin automatically adds explicit return type annotations to:
- ✅ Function declarations
- ✅ Arrow functions
- ✅ Class methods
- ✅ Function expressions
- ✅ Async functions (including
Promisereturn types)
Functions that already have explicit return types are skipped to avoid duplication.
Examples
Function Declaration
Before:
function sum(a: number, b: number) {
return a + b;
}After:
function sum(a: number, b: number): number {
return a + b;
}Arrow Function
Before:
const multiply = (a: number, b: number) => {
return a * b;
};After:
const multiply = (a: number, b: number): number => {
return a * b;
};Class Method
Before:
class Calculator {
add(a: number, b: number) {
return a + b;
}
}After:
class Calculator {
add(a: number, b: number): number {
return a + b;
}
}Function Expression
Before:
const handler = function (event: string) {
return event.length;
};After:
const handler = function (event: string): number {
return event.length;
};Async Function
Before:
async function fetchData(url: string) {
return fetch(url);
}After:
async function fetchData(url: string): Promise<Response> {
return fetch(url);
}Existing Return Types (Skipped)
Functions with existing return types are left unchanged:
Before & After:
function testVoid(): void {
console.log("testVoid");
}How It Works
The plugin uses TypeScript's type checker to infer return types for functions that don't have explicit return type annotations. It:
- Parses your TypeScript code using TypeScript's compiler API
- Uses the type checker to infer return types
- Adds explicit return type annotations to functions that don't have them
- Preserves all formatting and existing code structure
- Works seamlessly with Prettier's formatting pipeline
Requirements
- Node.js 14+
- Prettier 3.6+
- TypeScript 5.9+
License
MIT © 2025 Gavin Harris
