Claude
Skills
Sign in
Back

typescript-type-system

Included with Lifetime
$97 forever

Use when working with TypeScript's type system including strict mode, advanced types, generics, type guards, and compiler configuration.

General

What this skill does


# TypeScript Type System

Master TypeScript's type system features to write type-safe code. This
skill focuses exclusively on TypeScript language capabilities.

## TypeScript Compiler

```bash
# Type check without emitting files
tsc --noEmit

# Type check with specific config
tsc --noEmit -p tsconfig.json

# Show compiler version
tsc --version

# Watch mode for development
tsc --noEmit --watch
```

## Strict Mode Configuration

**tsconfig.json strict mode options:**

```json
{
  "compilerOptions": {
    "strict": true,                           // Enables all strict
    "noImplicitAny": true,                    // Error on 'any'
    "strictNullChecks": true,                 // null must be explicit
    "strictFunctionTypes": true,              // Stricter function types
    "strictBindCallApply": true,              // Strict bind/call/apply
    "strictPropertyInitialization": true,     // Class init required
    "noImplicitThis": true,                   // Error on 'this' any
    "alwaysStrict": true,                     // Parse strict mode
    "useUnknownInCatchVariables": true        // Catch is 'unknown'
  }
}
```

## Essential Compiler Options

```json
{
  "compilerOptions": {
    // Type Checking
    "exactOptionalPropertyTypes": true,       // Distinguish undefined from missing
    "noFallthroughCasesInSwitch": true,      // Prevent fallthrough in switch
    "noImplicitOverride": true,               // Require 'override' keyword
    "noImplicitReturns": true,                // All code paths must return
    "noPropertyAccessFromIndexSignature": true, // Require bracket notation for index
    "noUncheckedIndexedAccess": true,         // Index signatures return T | undefined
    "noUnusedLocals": true,                   // Error on unused local variables
    "noUnusedParameters": true,               // Error on unused parameters

    // Module Resolution
    "moduleResolution": "bundler",            // Modern bundler resolution
    "resolveJsonModule": true,                // Import JSON files
    "allowImportingTsExtensions": true,       // Import .ts/.tsx files
    "allowSyntheticDefaultImports": true,     // Allow default imports from modules
    "esModuleInterop": true,                  // Emit helpers for CommonJS interop

    // Emit
    "declaration": true,                      // Generate .d.ts files
    "declarationMap": true,                   // Source maps for .d.ts
    "sourceMap": true,                        // Generate .map files
    "removeComments": false,                  // Preserve comments in output
    "importHelpers": true,                    // Import helpers from tslib

    // Interop Constraints
    "isolatedModules": true,                  // Each file can be transpiled separately
    "allowArbitraryExtensions": true,         // Allow imports with any extension
    "verbatimModuleSyntax": false,            // Preserve import/export syntax

    // Skip Checks
    "skipLibCheck": true                      // Skip .d.ts file checking
  }
}
```

## Advanced Type Patterns

### Union and Intersection Types

```typescript
// Union types (OR)
type Status = "pending" | "active" | "completed";
type ID = string | number;
type Result = Success | Error;

// Intersection types (AND)
type User = Person & Employee;
type Props = BaseProps & { extended: true };

// Discriminated unions
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number }
  | { kind: "rectangle"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.size ** 2;
    case "rectangle":
      return shape.width * shape.height;
  }
}
```

### Generics

```typescript
// Basic generics
function identity<T>(value: T): T {
  return value;
}

// Generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Multiple type parameters
function merge<T, U>(obj1: T, obj2: U): T & U {
  return { ...obj1, ...obj2 };
}

// Generic interfaces
interface Repository<T> {
  find(id: string): Promise<T | null>;
  save(entity: T): Promise<T>;
  delete(id: string): Promise<void>;
}

// Generic classes
class DataStore<T extends { id: string }> {
  private items = new Map<string, T>();

  add(item: T): void {
    this.items.set(item.id, item);
  }

  get(id: string): T | undefined {
    return this.items.get(id);
  }
}

// Default type parameters
type Response<T = unknown> = {
  data: T;
  status: number;
};
```

### Conditional Types

```typescript
// Basic conditional type
type IsString<T> = T extends string ? true : false;

// Distributive conditional types
type Extract<T, U> = T extends U ? T : never;
type Exclude<T, U> = T extends U ? never : T;

// Infer keyword
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type Parameters<T> = T extends (...args: infer P) => any ? P : never;

// Nested conditionals
type Flatten<T> = T extends Array<infer U> ? U : T;
type DeepFlatten<T> = T extends Array<infer U> ? DeepFlatten<U> : T;

// Conditional type with constraints
type NonNullable<T> = T extends null | undefined ? never : T;
```

### Mapped Types

```typescript
// Make all properties optional
type Partial<T> = {
  [P in keyof T]?: T[P];
};

// Make all properties required
type Required<T> = {
  [P in keyof T]-?: T[P];
};

// Make all properties readonly
type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

// Pick specific properties
type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};

// Omit specific properties
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

// Transform property types
type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};

// Key remapping in mapped types
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

// Filter properties by type
type PickByType<T, U> = {
  [P in keyof T as T[P] extends U ? P : never]: T[P];
};
```

### Template Literal Types

```typescript
// Basic template literals
type EventName = "click" | "focus" | "blur";
type Handler = `on${Capitalize<EventName>}`; // "onClick" | "onFocus" | "onBlur"

// Combining template literals
type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE";
type Endpoint = `/api/${string}`;
type Route = `${HTTPMethod} ${Endpoint}`;

// Extract pattern from template
type ExtractRouteParams<T extends string> =
  T extends `${string}:${infer Param}/${infer Rest}`
    ? Param | ExtractRouteParams<Rest>
    : T extends `${string}:${infer Param}`
    ? Param
    : never;

type Params = ExtractRouteParams<"/users/:userId/posts/:postId">; // "userId" | "postId"

// Uppercase/Lowercase/Capitalize/Uncapitalize
type UppercaseKeys<T> = {
  [K in keyof T as Uppercase<string & K>]: T[K];
};
```

## Type Narrowing

### Type Guards

```typescript
// typeof type guards
function process(value: string | number) {
  if (typeof value === "string") {
    return value.toUpperCase(); // value is string
  }
  return value.toFixed(2); // value is number
}

// instanceof type guards
class Dog {
  bark() {}
}
class Cat {
  meow() {}
}

function makeSound(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark(); // animal is Dog
  } else {
    animal.meow(); // animal is Cat
  }
}

// in operator narrowing
type Fish = { swim: () => void };
type Bird = { fly: () => void };

function move(animal: Fish | Bird) {
  if ("swim" in animal) {
    animal.swim(); // animal is Fish
  } else {
    animal.fly(); // animal is Bird
  }
}

// Custom type guards
function isString(value: unknown): value is string {
  return typeof value === "string";
}

function isUser(obj: unknown): obj is { name: string; age: number } {
  return (
    typeof obj === "object" &&
    obj !== null &&
    "name" in obj &&
    "age" in obj &&
    typeof obj.name === "string" &&
    typeof obj.age === "number"
  );
}

// Assertion functions
function assert(condition: unknown, msg?: stri

Related in General