TypeScript Integration

P5 Svelte is built with TypeScript from the ground up, providing excellent type safety and developer experience. This guide will show you how to leverage TypeScript effectively in your sketches.

Type Definitions

Core Types

// lib/core/types.ts
export type P5Extended = p5 & {
  [key: string]: any;  // Custom properties
};

export interface Sketch {
  setup?: (p5: P5Extended) => void;
  draw?: (p5: P5Extended) => void;
  mousePressed?: (p5: P5Extended) => void;
  // ... other event handlers
}

export interface P5Configuration {
  width?: number;
  height?: number;
  backgroundColor?: string;
  frameRate?: number;
  antialias?: boolean;
}

Using Types in Sketches

Basic Usage

import type { Sketch, P5Extended } from '$lib/core/types';

interface GameState {
  score: number;
  isPlaying: boolean;
}

const sketch: Sketch = {
  setup: (p5: P5Extended) => {
    p5._state = {
      score: 0,
      isPlaying: false
    } as GameState;
  }
};

With Custom Types

interface Particle {
  x: number;
  y: number;
  velocity: { x: number; y: number };
}

interface SketchState {
  particles: Particle[];
}

const sketch: Sketch = {
  setup: (p5: P5Extended) => {
    p5._state = {
      particles: []
    } as SketchState;
  }
};

Type-Safe State Management

Svelte Store Types
import { writable } from 'svelte/store';

interface AppSettings {
  theme: 'light' | 'dark';
  frameRate: number;
  showFPS: boolean;
}

export const settings = writable<AppSettings>({
  theme: 'light',
  frameRate: 60,
  showFPS: true
});
Component Props
<script lang="ts">export let sketch;
export let config = {};
</script>

Advanced Types

Utility Types

type Vector = {
  x: number;
  y: number;
};

type Dimension = {
  width: number;
  height: number;
};

Type Guards

function isVector(obj: any):
  obj is Vector {
  return 'x' in obj
    && 'y' in obj;
}

Debug Types

type Debug = {
  logs: string[];
  isDebug: boolean;
  level: 'info' | 'warn' | 'error';
};

Best Practices

TypeScript Tips:

  • Always define interfaces for state objects
  • Use strict type checking (strict: true in tsconfig.json)
  • Leverage type inference when possible
  • Document complex types with JSDoc comments

Configuration

tsconfig.json

{
  "extends": "./.svelte-kit/tsconfig.json",
  "compilerOptions": {
    "strict": true,
    "allowUnreachableCode": false,
    "exactOptionalPropertyTypes": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true
  }
}

Next Steps

Now that you understand TypeScript integration, explore the Examples section to see these concepts in action.