Introduction to Serverless Functions in TypeScript
Serverless computing fundamentally changes the approach to developing and deploying applications. Instead of managing servers, developers focus exclusively on writing code. AWS Lambda is the leading service for creating serverless functions, and TypeScript adds the reliability of static typing to this.
In this article, we will thoroughly examine how to create, configure, and deploy a serverless function in TypeScript using AWS Lambda. You will learn how to write efficient code, handle events, and integrate Lambda with other AWS services.
What is AWS Lambda and Why TypeScript?
AWS Lambda Basics
AWS Lambda is a compute service that runs your code in response to events and automatically manages compute resources. You pay only for the actual execution time used (rounded up to 1 ms).
Key features:
- Event-driven architecture — the function is triggered when an event occurs (HTTP request, file upload to S3, change in DynamoDB)
- Automatic scaling — from a single request to thousands simultaneously
- Multi-language support — Node.js (TypeScript), Python, Java, Go, .NET
- Free tier — 1 million requests per month (within the Free Tier)
Advantages of TypeScript for Lambda
TypeScript is a superset of JavaScript that adds static typing. For serverless functions, this provides:
- Fewer runtime errors — the compiler catches type mismatches before deployment
- Better code documentation — types serve as self-documentation
- Support for modern features — async/await, decorators, generics
- Integration with AWS SDK — full types for all AWS services
Creating and Configuring a Lambda Function in TypeScript
Step 1: Project Initialization
Let's create a new project and install the necessary dependencies:
mkdir my-lambda-functioncd my-lambda-functionnpm init -ynpm install --save-dev typescript @types/node aws-sdknpm install --save-dev @types/aws-lambdaStep 2: TypeScript Configuration
Create a tsconfig.json file:
{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "lib": ["ES2020"], "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "declaration": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"]}Step 3: Writing the Lambda Function
Create a src directory and a src/handler.ts file:
import { Context, APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
interface UserData { userId: string; name: string; email: string;}
export const handler = async ( event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => { console.log('Event:', JSON.stringify(event, null, 2)); console.log('Context:', context);
try { // Parsing the request body const body: UserData = JSON.parse(event.body || '{}');
// Data validation if (!body.userId || !body.name || !body.email) { return { statusCode: 400, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }, body: JSON.stringify({ message: 'Missing required fields: userId, name, email' }) }; }