10 Prompts for Generating JavaScript and TypeScript Code
JavaScript and TypeScript dominate modern web development—from React frontends to Node.js backends and utility libraries. But writing boilerplate, handling edge cases, and structuring code often eats up hours. The right prompts can turn an AI assistant into a senior engineer who writes clean, type-safe, and production-ready code. This guide gives you 10 specific prompts, each with a real-world example, so you can generate high-quality JS/TS code in seconds.
Why Use Prompts for Code Generation?
Instead of manually typing every function, prompt engineering lets you describe your intent and get a complete implementation. According to GitHub’s 2025 Octoverse report, developers using AI-assisted coding tools save an average of 55% of time on routine tasks like writing tests, parsing data, or setting up components. The key is crafting prompts that specify language, framework, edge cases, and style. Below, you’ll find prompts for React components, Node.js APIs, TypeScript types, utility functions, and more.
1. React Functional Component with TypeScript Props
Task: Generate a reusable React component with typed props, default values, and basic styling.
Prompt:
Create a React functional component in TypeScript called `UserCard`. It accepts `name: string`, `email: string`, and optional `avatarUrl?: string`. Include a default avatar if `avatarUrl` is not provided. Use CSS-in-JS with a `style` object (no external libraries). Export the component as default.
Example output (abbreviated):
import React from 'react';
interface UserCardProps {
name: string;
email: string;
avatarUrl?: string;
}
const UserCard: React.FC<UserCardProps> = ({ name, email, avatarUrl }) => {
const styles = {
card: { border: '1px solid #ddd', padding: '16px', borderRadius: '8px' },
avatar: { width: '50px', height: '50px', borderRadius: '50%' },
};
return (
<div style={styles.card}>
<img
src={avatarUrl || 'https://via.placeholder.com/50'}
alt={name}
style={styles.avatar}
/>
<h2>{name}</h2>
<p>{email}</p>
</div>
);
};
export default UserCard;
2. Node.js Express Middleware for Authentication
Task: Build a middleware function that verifies a JWT token from the Authorization header and attaches the decoded user to the request object.
Prompt:
Write a TypeScript Express middleware function `authMiddleware` that:
- Reads the `Authorization` header (format: `Bearer <token>`)
- Verifies the JWT using a secret from environment variable `JWT_SECRET`
- If valid, attaches decoded payload to `req.user` (extend Express Request type)
- If invalid or missing, returns 401 with a JSON error message
- Use `jsonwebtoken` library
Example output (abbreviated):
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
declare global {
namespace Express {
interface Request {
user?: { id: string; email: string };
}
}
}
export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing or invalid token' });
}
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { id: string; email: string };
req.user = decoded;
next();
} catch (err) {
return res.status(401).json({ error: 'Token invalid or expired' });
}
};
3. TypeScript Utility Type for Deep Partial
Task: Create a generic utility type that makes all nested properties optional.
Prompt:
Define a TypeScript type `DeepPartial<T>` that recursively makes every property in `T` optional, including nested objects and arrays. Use conditional types and mapped types. Provide a usage example with a `User` interface containing nested `address` and `settings`.
Example output (abbreviated):
type DeepPartial<T> = T extends object
? { [P in keyof T]?: DeepPartial<T[P]> }
: T;
interface User {
id: number;
name: string;
address: { street: string; city: string };
}
const partialUser: DeepPartial<User> = { name: 'Alice' }; // valid
const partialWithAddress: DeepPartial<User> = { address: { city: 'NYC' } }; // valid
4. React Custom Hook for Debouncing Input
Task: Write a custom React hook that debounces a value by a specified delay.
Prompt:
Implement a custom React hook `useDebounce<T>(value: T, delay: number): T` that returns the debounced value after the delay. Use `useState` and `useEffect`. Ensure it cleans up the timer on unmount. Show a usage example in a search input component.
Example output (abbreviated):
import { useState, useEffect } from 'react';
function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
export default useDebounce;
5. Async Function with Retry Logic
Task: Write a generic async function that retries a failing operation with exponential backoff.
Prompt:
Create a TypeScript function `retryAsync<T>(fn: () => Promise<T>, maxRetries: number = 3): Promise<T>` that:
- Calls `fn`, and if it throws, waits for `2^attempt` seconds before retrying
- Stops after `maxRetries` attempts and throws the last error
- Provide a usage example with a mock API call that fails intermittently
Example output (abbreviated):
async function retryAsync<T>(fn: () => Promise<T>, maxRetries: number = 3): Promise<T> {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
if (attempt === maxRetries - 1) throw error;
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw new Error('Unexpected error');
}
// Usage
const fetchData = async () => {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('Network error');
return response.json();
};
retryAsync(fetchData).then(data => console.log(data));
6. Zod Schema for User Registration
Task: Define a validation schema using Zod for a user registration form.
Prompt:
Write a Zod schema `userRegistrationSchema` in TypeScript that validates:
- `email`: valid email format
- `password`: min 8 chars, must contain a number and a special character
- `age`: optional number, must be between 18 and 120
- `name`: string, min 2 chars, max 50 chars
Include a parse example with error handling.
Example output (abbreviated):
import { z } from 'zod';
const userRegistrationSchema = z.object({
email: z.string().email('Invalid email'),
password: z
.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[0-9]/, 'Must contain a number')
.regex(/[!@#$%^&*]/, 'Must contain a special character'),
age: z.number().min(18).max(120).optional(),
name: z.string().min(2).max(50),
});
const result = userRegistrationSchema.safeParse({
email: 'test@example.com',
password: 'Hello1!',
name: 'Alice',
});
if (!result.success) {
console.log(result.error.flatten());
}
7. Node.js File Upload Handler with Multer
Task: Build an Express endpoint that accepts a single file upload and stores it on disk.
Prompt:
Create a TypeScript Express route `POST /upload` that:
- Uses `multer` to accept a single file with field name `file`
- Saves the file to `./uploads/` with a unique filename (timestamp + original extension)
- Returns JSON with `{ filename, size }` on success
- Limits file size to 5 MB and only allows images (jpeg, png, gif)
- Handles multer errors gracefully with a 400 status
Example output (abbreviated):
import multer from 'multer';
import path from 'path';
import express from 'express';
const storage = multer.diskStorage({
destination: './uploads/',
filename: (req, file, cb) => {
const uniqueName = Date.now() + path.extname(file.originalname);
cb(null, uniqueName);
},
});
const upload = multer({
storage,
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const allowed = /jpeg
|jpg|png|gif/;
const extname = allowed.test(path.extname(file.originalname).toLowerCase());
if (extname) {
cb(null, true);
} else {
cb(new Error('Only images allowed'));
}
},
});
const app = express();
app.post('/upload', (req, res) => {
upload.single('file')(req, res, (err) => {
if (err) return res.status(400).json({ error: err.message });
res.json({ filename: req.file!.filename, size: req.file!.size });
});
});
8. TypeScript Generic Sort Function
Task: Write a generic function that sorts an array of objects by a given key.
Prompt:
Implement a TypeScript function `sortByKey<T>(arr: T[], key: keyof T, order: 'asc' | 'desc' = 'asc'): T[]` that returns a new sorted array without mutating the original. Handle string and number values. Provide a usage example with an array of `{ name: string, age: number }`.
Example output (abbreviated):
function sortByKey<T>(arr: T[], key: keyof T, order: 'asc' | 'desc' = 'asc'): T[] {
return [...arr].sort((a, b) => {
const aVal = a[key];
const bVal = b[key];
if (typeof aVal === 'string' && typeof bVal === 'string') {
return order === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
}
if (typeof aVal === 'number' && typeof bVal === 'number') {
return order === 'asc' ? aVal - bVal : bVal - aVal;
}
return 0;
});
}
const users = [{ name: 'Bob', age: 30 }, { name: 'Alice', age: 25 }];
const sorted = sortByKey(users, 'age', 'asc');
console.log(sorted); // [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]
9. React Context with TypeScript
Task: Create a theme context that provides light/dark mode to the component tree.
Prompt:
Build a React context `ThemeContext` in TypeScript that:
- Has a state `theme: 'light' | 'dark'`
- Provides a `toggleTheme` function
- Includes a `ThemeProvider` component that wraps children
- Create a custom hook `useTheme` for consuming the context
- Use `createContext` with a default value of `undefined` and throw an error if used outside provider
Example output (abbreviated):
import React, { createContext, useContext, useState, ReactNode } from 'react';
interface ThemeContextType {
theme: 'light' | 'dark';
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [theme, setTheme] = useState<'light' | 'dark'>('light');
const toggleTheme = () => setTheme(prev => (prev === 'light' ? 'dark' : 'light'));
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};
export const useTheme = (): ThemeContextType => {
const context = useContext(ThemeContext);
if (!context) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
};
10. Command-Line Tool with Node.js
Task: Write a simple CLI that reads a JSON file and pretty-prints it.
Prompt:
Create a Node.js script `pretty-json.js` that:
- Accepts a file path as a command-line argument (e.g., `node pretty-json.js data.json`)
- Reads the file, parses it as JSON, and prints it indented with 2 spaces
- If the file doesn’t exist or JSON is invalid, print a helpful error message to stderr and exit with code 1
- Use only Node.js built-in modules (`fs`, `path`, `process`)
Example output (abbreviated):
const fs = require('fs');
const path = require('path');
if (process.argv.length < 3) {
console.error('Usage: node pretty-json.js <file>');
process.exit(1);
}
const filePath = path.resolve(process.argv[2]);
try {
const data = fs.readFileSync(filePath, 'utf8');
const json = JSON.parse(data);
console.log(JSON.stringify(json, null, 2));
} catch (err) {
if (err.code === 'ENOENT') {
console.error('Error: File not found');
} else {
console.error('Error: Invalid JSON');
}
process.exit(1);
}
Conclusion
These 10 prompts cover the most common tasks in JavaScript and TypeScript development—from React components and custom hooks to Node.js middleware, validation schemas, and CLI tools. By using specific, well-structured prompts, you can generate production-ready code in seconds, freeing up time for logic and architecture. Copy these prompts into your favorite AI tool, adjust the parameters to your project, and start coding faster. For more advanced patterns, explore the official TypeScript handbook (typescriptlang.org/docs/handbook) and React documentation (react.dev).
Happy coding!
Comments