Type-safe identifiers with branded types for Google Antigravity IDE
# TypeScript Branded Types Patterns for Google Antigravity
Master branded types in TypeScript with Google Antigravity IDE. This comprehensive guide covers creating nominal types, type-safe identifiers, validation patterns, and advanced branding techniques that prevent type confusion and catch bugs at compile time.
## Configuration
Configure your Antigravity environment for branded types:
```typescript
// .antigravity/branded-types.ts
export const brandedConfig = {
patterns: ["nominal", "validation", "refinement"],
strictness: "maximum",
runtime: {
validation: true,
assertions: true
}
};
```
## Basic Branded Types
Create nominal types with brands:
```typescript
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { [brand]: B };
type UserId = Brand<string, "UserId">;
type PostId = Brand<string, "PostId">;
type Email = Brand<string, "Email">;
type Timestamp = Brand<number, "Timestamp">;
function createUserId(id: string): UserId {
return id as UserId;
}
function createPostId(id: string): PostId {
return id as PostId;
}
function getUser(userId: UserId): Promise<User> {
return fetch(`/api/users/${userId}`).then(r => r.json());
}
function getPost(postId: PostId): Promise<Post> {
return fetch(`/api/posts/${postId}`).then(r => r.json());
}
const userId = createUserId("user-123");
const postId = createPostId("post-456");
getUser(userId);
getUser(postId);
```
## Validated Branded Types
Combine branding with runtime validation:
```typescript
type ValidationResult<T> =
| { success: true; value: T }
| { success: false; error: string };
function createEmail(input: string): ValidationResult<Email> {
const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
if (!emailRegex.test(input)) {
return { success: false, error: "Invalid email format" };
}
return { success: true, value: input as Email };
}
type PositiveNumber = Brand<number, "PositiveNumber">;
function createPositiveNumber(n: number): ValidationResult<PositiveNumber> {
if (n <= 0) {
return { success: false, error: "Number must be positive" };
}
return { success: true, value: n as PositiveNumber };
}
type NonEmptyString = Brand<string, "NonEmptyString">;
function createNonEmptyString(s: string): ValidationResult<NonEmptyString> {
const trimmed = s.trim();
if (trimmed.length === 0) {
return { success: false, error: "String cannot be empty" };
}
return { success: true, value: trimmed as NonEmptyString };
}
```
## Opaque Types Pattern
Create fully opaque branded types:
```typescript
type Opaque<T, K extends string> = T & { readonly __opaque__: K };
type Currency = Opaque<number, "Currency">;
type USD = Opaque<Currency, "USD">;
type EUR = Opaque<Currency, "EUR">;
const usd = (amount: number): USD => amount as USD;
const eur = (amount: number): EUR => amount as EUR;
function addUSD(a: USD, b: USD): USD {
return ((a as number) + (b as number)) as USD;
}
const price1 = usd(10);
const price2 = usd(20);
const euroPrice = eur(15);
addUSD(price1, price2);
addUSD(price1, euroPrice);
```
## Branded Type Utilities
Build reusable branding utilities:
```typescript
type Branded<T, B extends string> = T & { readonly __brand: B };
type Unbrand<T> = T extends Branded<infer U, string> ? U : T;
type RebrandAs<T, B extends string> = Branded<Unbrand<T>, B>;
function brand<T, B extends string>(value: T): Branded<T, B> {
return value as Branded<T, B>;
}
function unbrand<T extends Branded<unknown, string>>(value: T): Unbrand<T> {
return value as Unbrand<T>;
}
type Slug = Branded<string, "Slug">;
type URL = Branded<string, "URL">;
function slugToUrl(slug: Slug, baseUrl: string): URL {
return brand<string, "URL">(`${baseUrl}/${unbrand(slug)}`);
}
```
## Domain Modeling with Brands
Model domain concepts safely:
```typescript
type OrderId = Brand<string, "OrderId">;
type CustomerId = Brand<string, "CustomerId">;
type ProductId = Brand<string, "ProductId">;
type Quantity = Brand<number, "Quantity">;
type Price = Brand<number, "Price">;
interface Order {
id: OrderId;
customerId: CustomerId;
items: Array<{
productId: ProductId;
quantity: Quantity;
unitPrice: Price;
}>;
total: Price;
}
function calculateTotal(items: Order["items"]): Price {
const total = items.reduce(
(sum, item) => sum + (item.quantity as number) * (item.unitPrice as number),
0
);
return total as Price;
}
```
## Best Practices
Follow these guidelines for branded types:
1. **Use unique symbols** - Ensure true nominal typing
2. **Validate at boundaries** - Check inputs at system edges
3. **Keep brands descriptive** - Name brands clearly
4. **Combine with validation** - Add runtime checks
5. **Document brand meanings** - Explain what brands represent
6. **Use utility types** - Build reusable branding helpers
Google Antigravity IDE provides intelligent branded type suggestions and automatic validation scaffolding for type-safe domain modeling.This TypeScript prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their typescript implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For TypeScript projects, consider mentioning your framework version, coding style, and any specific libraries you're using.