TypeScript Support DEV

Complete TypeScript definitions for full IDE support, type checking, and runtime binding validation.

Sandbox Examples: TypeScript examples run in isolated iframes demonstrating type-safe patterns and runtime validation features.

Overview

WildflowerJS provides comprehensive TypeScript support through:

  • Complete type definitions - Full .d.ts file with 1200+ lines covering all APIs
  • Generic components - Type-safe state management with ComponentDefinition<TState>
  • Runtime validation - Catch binding errors during development with types property
  • JSDoc annotations - Rich documentation in source for JavaScript users
  • IDE integration - IntelliSense, autocomplete, and inline documentation

Installation

The TypeScript definitions are included in the WildflowerJS package. For TypeScript projects:

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*.ts", "wildflowerJS.d.ts"]
}

Script-tag projects: the global typings

The package also ships types/wildflower.global.d.ts (from 1.5.1), a second, opt-in declaration for the script-tag wildflower global. It infers this inside a definition from the literal you pass, so this.count, this.doubled, this.pools.enemies and this.stores.cart complete without any TypeScript in the app. Reference it from a jsconfig.json or a triple-slash directive, alongside or instead of the module typings:

/// <reference path="node_modules/wildflowerjs/types/wildflower.global.d.ts" />

wildflower.component('counter', {
    state: { count: 0 },
    computed: { doubled() { return this.count * 2 } },   // this.count is a number
    increment() { this.count++ }
});

For JavaScript projects, you can still benefit from type definitions through JSDoc comments and IDE support:

// Enable TypeScript checking in JS files via JSDoc
// @ts-check

/** @type {import('./wildflowerJS').WildflowerOptions} */
const options = {
    debug: true,
    autoInit: false
};

const wf = new WildflowerJS('#app', options);

Type Definitions

WildflowerJS exports the following key types:

Core Types

Type Description
WildflowerJSMain framework class
WildflowerOptionsFramework initialization options
ComponentDefinition<T>Component definition with typed state
ComponentInstanceRuntime component instance
ComponentStateBase state type

Router Types

Type Description
RouteManagerRouter class
RouteManagerOptionsRouter configuration
RouteConfigRoute definition
RouteCurrent route state
RouteGuardNavigation guard function

Store Types

Type Description
StoreConfig<T>Store definition with typed state
StoreContext<T>Store instance with typed methods

Typed Components

Define components with strongly-typed state for full IDE support:

// Define a typed interface for your component state
interface CounterState {
    count: number;
    step: number;
    label: string;
}

// Use ComponentDefinition<T> for type-safe components
const counterDef: ComponentDefinition<CounterState> = {
    state: {
        count: 0,
        step: 1,
        label: 'Counter'
    },

    computed: {
        doubled() {
            // ContextProxy auto-resolves state properties
            // IDE autocomplete shows: count, step, label
            return this.count * 2;
        }
    },

    increment() {
        this.count += this.step;
    },

    setStep(value: number) {
        // TypeScript ensures value is a number
        this.step = value;
    }
};

wildflower.component('typed-counter', counterDef);

With this definition, TypeScript provides:

  • Autocomplete - Type this. and see all state and computed properties
  • Error detection - this.invalid shows a red squiggle
  • Type checking - this.count = "string" is caught at compile time
  • Refactoring - Rename a property and all references update

Typed Stores

Create strongly-typed stores with full IDE support:

interface CartState {
    items: Array<{ id: number; name: string; price: number; quantity: number }>;
    total: number;
}

const storeConfig: StoreConfig<CartState> = {
    state: {
        items: [],
        total: 0
    },
    computed: {
        itemCount() {
            return this.items.reduce((sum, item) => sum + item.quantity, 0);
        }
    },
    watch: {
        items(newItems, oldItems) {
            this.total = newItems.reduce(
                (sum, item) => sum + item.price * item.quantity,
                0
            );
        }
    },
    addItem(item: { id: number; name: string; price: number }) {
        this.items.push({ ...item, quantity: 1 });
    },
    removeItem(id: number) {
        this.items = this.items.filter(i => i.id !== id);
    }
};

const cartStore: StoreContext<CartState> = wf.store('cart', storeConfig);

Runtime Binding Validation

WildflowerJS provides runtime type checking for development builds through the types property:

TypeScript Example Runtime Type Validation Open Full Example
Runtime Type Definition:
wildflower.component('validated-form', {
    state: {
        username: '',
        age: 0,
        isActive: false,
        tags: [],
        metadata: {}
    },
    // Runtime type validation (development mode)
    types: {
        username: 'string',
        age: 'number',
        isActive: 'boolean',
        tags: 'array',
        metadata: 'object'
    },
    updateAge(event, element) {
        // Framework validates: is the new value a number?
        this.age = parseInt(element.value, 10);
    }
});
Development Feature: Type mismatches are logged as warnings in development mode. This helps catch errors like binding a string to a number field or assigning an array where an object is expected.

Supported Runtime Types

Type String JavaScript Type Example Values
'string'string'', 'hello'
'number'number0, 42, 3.14
'boolean'booleantrue, false
'array'Array[], [1, 2, 3]
'object'object{}, { key: 'value' }
'function'function() => {}
'any'anyNo validation

IDE Features

With TypeScript definitions, your IDE provides:

IntelliSense & Autocomplete

  • Property suggestions - See all state properties when typing this.
  • Method signatures - View parameter types and return values
  • Quick documentation - Hover over methods to see JSDoc comments
  • Error detection - Red squiggles for type mismatches

Supported IDEs

  • VS Code - Full TypeScript support out of the box
  • WebStorm - Excellent TypeScript integration
  • Vim/Neovim - With TypeScript language server
  • Any IDE with TypeScript support

Example: IDE Autocomplete

// After typing "wf.", IDE suggests:
// - component()
// - store()
// - getStore()
// - router()
// - plugin()
// - on()
// - ... all public methods

// After typing "this." in a component:
// - All state properties (auto-resolved)
// - Computed properties (auto-resolved)

// After typing "router.", IDE suggests:
// - navigate()
// - onRoute()
// - beforeEach()
// - getCurrentRoute()
// - ... all router methods

Best Practices

Define Interfaces for Complex State

// Define interface for clarity and reuse
interface UserState {
    profile: {
        name: string;
        email: string;
        avatar: string;
    };
    preferences: {
        theme: 'light' | 'dark';
        notifications: boolean;
    };
    isLoading: boolean;
}

// Use the interface in component definition
const userComponent: ComponentDefinition<UserState> = {
    state: {
        profile: { name: '', email: '', avatar: '' },
        preferences: { theme: 'light', notifications: true },
        isLoading: false
    }
};

Use Runtime Types for JavaScript Projects

// Even without TypeScript, get runtime validation
wildflower.component('user-form', {
    state: {
        name: '',
        age: 0,
        email: ''
    },
    types: {
        name: 'string',
        age: 'number',
        email: 'string'
    }
});

Combine TypeScript and Runtime Validation

// TypeScript catches compile-time errors
// Runtime types catch data-flow errors (e.g., API responses)
interface FormState {
    count: number;
    name: string;
}

const formDef: ComponentDefinition<FormState> = {
    state: { count: 0, name: '' },
    types: { count: 'number', name: 'string' }, // Runtime check

    async loadFromAPI() {
        const data = await fetch('/api/data').then(r => r.json());
        // TypeScript ensures data shape at compile time
        // Runtime types warn if API returns wrong types
        this.count = data.count;
        this.name = data.name;
    }
};

Type Guards for Complex Logic

interface Item {
    id: number;
    type: 'product' | 'service';
    price: number;
}

function isProduct(item: Item): item is Item & { type: 'product' } {
    return item.type === 'product';
}

// In component methods:
processItem(item: Item) {
    if (isProduct(item)) {
        // TypeScript knows item.type is 'product' here
        this.calculateProductTax(item);
    }
}
Tip: Enable strict: true in your tsconfig.json for the best type checking experience. This catches more potential issues at compile time.