TypeScript Reference Guide
Quick reference for TypeScript types, interfaces, and patterns used in AI development.
Published: 1/1/2026
TypeScript Basics
1. Basic Types
// Primitives const city: string = "Paris"; const temperature: number = 20; const isRaining: boolean = false; // Arrays const cities: string[] = ["Paris", "London", "Tokyo"]; const temperatures: number[] = [20, 15, 25]; // Any type (avoid when possible!) let anything: any = "hello"; anything = 123; // This works, but defeats the purpose of TypeScript
2. Function Types
// Function with typed parameters and return type function greet(name: string): string { return `Hello, ${name}!`; } // Arrow function const greet = (name: string): string => { return `Hello, ${name}!`; }; // Async function async function getWeather(city: string): Promise<number> { const data = await fetchWeatherAPI(city); return data.temperature; // Returns a Promise<number> } // Void return (no return value) function logMessage(message: string): void { console.log(message); // No return statement }
3. Interfaces and Types
// Interface - defines object shape interface Destination { name: string; country: string; temperature: number; activities: string[]; } // Using the interface const paris: Destination = { name: "Paris", country: "France", temperature: 20, activities: ["Eiffel Tower", "Louvre", "Seine cruise"], }; // Optional properties interface TravelPlan { destination: string; startDate: string; endDate: string; budget?: number; // Optional - might not be provided } // Type alias (similar to interface) type Weather = { city: string; temp: number; condition: "sunny" | "cloudy" | "rainy"; // Union type };
4. Error Handling with Types
// Type guard for proper error handling async function chat(message: string): Promise<string> { try { const response = await openai.responses.create({ ... }); return response.output_text || 'No response'; } catch (error) { // Type guard: check if error is an instance of Error if (error instanceof Error) { return `Error: ${error.message}`; } // Check for OpenAI-specific errors if (error instanceof OpenAI.APIError) { if (error.status === 401) { return 'Invalid API key'; } if (error.status === 429) { return 'Rate limit exceeded'; } } return 'Unknown error occurred'; } }
5. Generic Types
// Generic function - works with any type function getFirstItem<T>(items: T[]): T | undefined { return items[0]; } const firstCity = getFirstItem(["Paris", "London"]); // Type: string const firstNumber = getFirstItem([1, 2, 3]); // Type: number // Promise is a generic type async function fetchData(): Promise<string> { // Returns a Promise that resolves to a string return "data"; } // Array is a generic type const cities: Array<string> = ["Paris", "Tokyo"]; // Same as: const cities: string[] = ['Paris', 'Tokyo'];
TypeScript Benefits You'll Experience
1. Autocomplete
Type in your editor and see:
const response = await openai.responses.; // Your editor shows all available methods: // - create() // - list() // - retrieve()
2. Catch Errors Early
// TypeScript catches this BEFORE running const temp: number = "hot"; // ❌ Error: Type 'string' is not assignable to type 'number' // Instead of discovering the error at runtime
3. Refactoring Safety
// Change a function signature function getWeather(city: string, unit: "C" | "F"): number { // ... } // TypeScript shows ALL places that need updating getWeather("Paris"); // ❌ Error: Expected 2 arguments, but got 1 getWeather("Paris", "K"); // ❌ Error: Argument of type '"K"' is not assignable to parameter of type '"C" | "F"'
4. Documentation
// Hover over functions to see documentation const response = await openai.responses.create(); // VS Code shows: // - Parameter types // - Return type // - Description
Common TypeScript Errors & Solutions
Error: "Cannot find module 'openai'"
Solution:
pnpm add openai
Error: "TS2304: Cannot find name 'process'"
Solution:
pnpm add -D @types/node
Make sure tsconfig.json includes:
{ "compilerOptions": { "types": ["node"] } }
Error: "Property 'content' does not exist"
Cause: Trying to access a property that might not exist.
Solution: Use optional chaining:
// ❌ Might error if message is undefined const content = response.choices[0].message.content; // ✅ Safe - returns undefined if any part is missing const content = response.choices[0]?.message?.content; // ✅ With default value const content = response.choices[0]?.message?.content || "No response";
Error: "Type 'string | null' is not assignable to type 'string'"
Cause: Value might be null, but you're treating it as always a string.
Solution:
// ❌ TypeScript knows content might be null const content: string = message.content; // ✅ Handle the null case const content: string = message.content || "No response"; // ✅ Or use the nullable type const content: string | null = message.content; if (content) { console.log(content); // TypeScript knows it's a string here }
TypeScript vs JavaScript: Quick Comparison
| Feature | JavaScript | TypeScript |
|---|---|---|
| Type safety | Runtime only | Compile-time + Runtime |
| Error detection | When code runs | As you type |
| IDE support | Basic | Excellent autocomplete |
| Refactoring | Manual search | Automated + safe |
| Learning curve | Easier start | Steeper but worth it |
| File extension | .js | .ts |
| Runs in browser | Yes, directly | No, compiles to JS first |
| Best for | Small scripts | Large applications |
Quick Tips
Use Type Inference
TypeScript can often figure out types automatically:
// TypeScript infers the type const city = "Paris"; // Type: string (inferred) const temp = 20; // Type: number (inferred) // No need to write: const city: string = "Paris";
Use Union Types
When a value can be one of several types:
type Status = "success" | "error" | "pending"; function updateStatus(status: Status) { // status can only be one of the three values }
Use Type Aliases for Readability
// Before function process(data: { name: string; age: number; city: string }) { // ... } // After type Person = { name: string; age: number; city: string; }; function process(data: Person) { // Much clearer! }
Related Resources
- MDN TypeScript Docs: typescriptlang.org
- TypeScript Playground: Try code in your browser
- Back to Setup Guide: Lesson 2: TypeScript Setup