Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
TypeScript Branded Types Patterns

TypeScript Branded Types Patterns

Type-safe identifiers with branded types for Google Antigravity IDE

TypeScriptType SafetyDomain ModelingAdvanced
by Antigravity AI
⭐0Stars
.antigravity
# 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.

When to Use This Prompt

This TypeScript prompt is ideal for developers working on:

  • TypeScript applications requiring modern best practices and optimal performance
  • Projects that need production-ready TypeScript code with proper error handling
  • Teams looking to standardize their typescript development workflow
  • Developers wanting to learn industry-standard TypeScript patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the TypeScript code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this TypeScript prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...