TypeScript Examples
TypeScript examples and patterns for using Metigan. Learn about type safety, type guards, and best practices for TypeScript integration.
Type-Safe Email Sending
type-safe.tsTypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import Metigan from 'metigan';
import type { EmailApiResponse, EmailSuccessResponse, EmailErrorResponse } from 'metigan';
const metigan = new Metigan({
apiKey: process.env.METIGAN_API_KEY!
});
// Type guard function
function isEmailSuccess(response: EmailApiResponse): response is EmailSuccessResponse {
return 'success' in response && response.success === true;
}
function isEmailError(response: EmailApiResponse): response is EmailErrorResponse {
return 'success' in response && response.success === false;
}
// Type-safe email sending
async function sendEmailTyped(): Promise<EmailSuccessResponse | null> {
const result: EmailApiResponse = await metigan.email.sendEmail({
from: 'sender@example.com',
recipients: ['recipient@example.com'],
subject: 'Hello from TypeScript!',
content: '<p>Type-safe email sending.</p>'
});
if (isEmailSuccess(result)) {
// TypeScript knows result is EmailSuccessResponse here
console.log('Tracking ID:', result.successfulEmails[0]?.trackingId);
return result;
}
if (isEmailError(result)) {
// TypeScript knows result is EmailErrorResponse here
console.error('Error:', result.error, result.message);
return null;
}
return null;
}Type Safety
Use type guards to narrow response types. This gives you full type safety and IntelliSense support in your IDE.