TypeScript
Rasti ships with TypeScript declarations out of the box. The types are bundled in the package and resolved automatically.
Components
In TypeScript the subclass form types best. The generics type props and state, the interpolations are ordinary expressions the compiler already checks, handlers are arrows that close over a typed this, and the class name is a value and a type — so no InstanceType alias and no annotated callbacks:
interface CounterProps { initial: number; label: string }
class Counter extends Component<CounterProps> {
timer: number | null = null; // instance fields declared normally
template() {
return this.html`
<div>
<span>${this.props.label}: ${this.props.initial}</span>
<button onClick=${() => this.increment()}>+</button>
</div>
`;
}
increment() { /* `this` and `this.props` are typed */ }
}
const counter: Counter = new Counter({ initial: 0, label: 'Clicks' }); // ✅ `Counter` is also a type
Counter.mount({ initial: 0, label: 'Clicks' }, document.body).increment(); // ✅ options and methods typed
With Component.create, pass the generics explicitly to type the resulting class. A template function receives the typed component as its argument, and as this, so its template is checked like a subclass's, with no annotations:
const Header = Component.create<{ title: string }>(({ props, html }) => html`
<header><h1>${props.title}</h1></header>
`);
new Header({ title: 'Todos' }); // ✅
// With a typed model:
const App = Component.create<{}, any, AppModel>(({ model, html }) => html`<main>...</main>`);
App.mount({ model: new AppModel() }, document.body);
Unlike a subclass, a component made with create is a value only: to use its name as a type, alias it (see Helper types).
Without generics, Component.create stays permissive (parity with JS):
const Plain = Component.create`<div></div>`;
new Plain({ anything: 'goes' }); // ✅
When a component is used with inner content (<${Card}>...</${Card}>), rasti injects a renderChildren function into its props at runtime. Declare it in P to use it:
interface CardProps { title: string; renderChildren?: () => any; }
const Card = Component.create<CardProps>(({ props, html }) => html`
<div class="card">
<h2>${props.title}</h2>
${props.renderChildren?.()}
</div>
`);
In the tagged form, the interpolations are typed by annotating their parameter with the component type instead (see Typing template interpolations).
Component.extend adds the object members to the instance type. Inside its methods, this is the extended component, and lifecycle overrides get their parameters typed automatically:
const Counter = Component.create<{ initial: number }>(({ html }) => html`<div>...</div>`).extend({
onCreate() {
this.state = new Model({ count: this.props.initial }); // `this` is typed
},
onChange(model, changed) { // parameters typed automatically
if ('count' in changed) this.render();
},
increment() { this.state.count++; },
});
Counter.mount({ initial: 0 }, document.body).increment(); // ✅ increment is typed
To read attributes off a typed state (or model) directly, define it as a named Model subclass with declaration merging and pass it as the S (or M) generic — then there are no casts anywhere:
class ScoreState extends Model<{ points: number }> {}
interface ScoreState { points: number } // exposes this.points
class Scoreboard extends Component<{}, ScoreState> {
onCreate() {
this.state = new ScoreState({ points: 0 });
this.state.points++; // ✅ typed, no cast
}
}
Models
Type the attributes with Model<YourAttrs>. Use declaration merging to surface the auto-generated getters/setters as instance properties:
import { Model } from 'rasti';
interface TodoAttrs { title: string; completed: boolean; }
class Todo extends Model<TodoAttrs> {
get defaults() { return { title: '', completed: false }; }
toggle() { this.completed = !this.completed; }
}
interface Todo extends TodoAttrs {} // Exposes this.title, this.completed
const t = new Todo({ title: 'x' });
t.title.toUpperCase(); // ✅
t.on('change:completed', (m, value) => value && /* boolean */ console.log('done'));
Helper types
import {
EventHandler,
RenderExpression,
ModelAttrs,
ComponentProps,
ComponentState,
ComponentModel,
} from 'rasti';
// `Counter` (defined above with Component.create) is a *value*. To use the name in
// type position, alias it once — now `Counter` is both a value and a type:
type Counter = InstanceType<typeof Counter>;
// Typed event handler with `this` bound to the component
const onClick: EventHandler<Counter, MouseEvent> = function(ev) {
this.props.initial;
};
// Typed render expression (`(component) => any`)
const renderLabel: RenderExpression<Counter> = ({ props }) => props.initial;
// Extract types from existing classes
type A = ModelAttrs<Todo>; // Todo extends Model → already a type, no alias
type P = ComponentProps<Counter>; // pass the instance; `ComponentProps<typeof Counter>` is `never`
type S = ComponentState<Counter>;
Components made with
Component.createare values, not types. To use one as a type outside its own template — as withCounterabove — addtype X = InstanceType<typeof X>next to the definition, or writeInstanceType<typeof X>inline. Inside its own template, useComponent<P, S, M>instead (see Typing template interpolations). Neither aModelsubclass nor a component authored as a subclass needs an alias, sinceclassalready declares both a value and a type.
A typed component is a Component, and a typed model a Model, so code written for any of them takes it. For any component class, write typeof Component<any>: typeof Component is a class whose constructor takes any options, which a component with required props is not.
function openDialog(dialog: Component) { document.body.append(dialog.el); }
openDialog(new Counter({ initial: 0 })); // ✅
const routes: Record<string, typeof Component<any>> = { counter: Counter, header: Header }; // ✅
Contexts
Type a context key with InjectionKey<T>, where T is the shape of the values it carries. At runtime it is a plain Symbol, so it keys the object provide() returns:
import { Component, InjectionKey } from 'rasti';
// form-control.ts
interface FormControlValues { id: string | null; describedBy: string | null; invalid: boolean; }
export const FormControl: InjectionKey<FormControlValues> = Symbol('formControl');
class Field extends Component<{ controlId: string; error?: string }> {
provide() {
const { controlId, error } = this.props;
return {
[FormControl]: { id: controlId, describedBy: error ? `${controlId}-error` : null, invalid: !!error },
};
}
}
class Input extends Component<{ id?: string }> {
template() {
const control = this.inject(FormControl); // Model<FormControlValues> & Partial<FormControlValues>
return this.html`<input id="${this.props.id || control.id}">`;
}
}
inject returns the provider's model typed by the key. Its values are Partial, because without a provider the model is empty. A plain Symbol or a string key reads as Record<string, any>.
Typing template interpolations
This section applies to the tagged Component.create form. In the subclass and create(fn) forms the template body is ordinary code inside a typed method, so its interpolations are checked without helpers — that is the simplest way to get full typing.
Functions inside a tagged template are any — rasti can't infer them from the surrounding string. How to type one depends on what rasti calls it with, and that depends on where it sits in the template.
Under
strict/noImplicitAny, an untyped interpolation callback is an error (TS7031/TS7006), not a silentany. In non-strict mode typing is opt-in.
| Interpolation | Called with | Type it with |
|---|---|---|
Content ${fn} or quoted attr attr="${fn}" |
The component, as its argument and as this |
An arrow annotated with the component type: ({ props }: C) => … |
Unquoted onX=${fn} |
(event, component, matched), with this the component |
satisfies EventHandler<C, E> |
Function passed to a child (handler=${fn}) |
Whatever the child calls it with | satisfies ChildProps['handler'] |
The component type C is Component<P, S, M> with the same generics passed to create, aliased next to the component. It is not a copy: it is the exact type of the component's instances.
interface ToggleProps { label: string; }
class ToggleState extends Model<{ active: boolean }> {}
interface ToggleState { active: boolean; }
type ToggleComponent = Component<ToggleProps, ToggleState>;
const Toggle = Component.create<ToggleProps, ToggleState>`
<button onClick=${(function() { this.state!.active = !this.state!.active; }) satisfies EventHandler<ToggleComponent, MouseEvent>}>
${({ props, state }: ToggleComponent) => `${props.label}: ${state!.active ? 'on' : 'off'}`}
</button>
`.extend({
onCreate() { this.state = new ToggleState({ active: false }); }
});
Inside its own template, a component can't use InstanceType<typeof Toggle>: the type of Toggle depends on the template itself, so TypeScript reports a circular reference (TS7022).
Content and quoted attributes receive the component as their argument, so annotating the parameter types everything they read. A function that reads this instead needs satisfies RenderExpression<C>, which types this as well:
${(function() { return this.props.label; }) satisfies RenderExpression<ToggleComponent>}
Unquoted handlers receive the event first, not the component. An annotated parameter still compiles there, since the template's expressions are any, and fails at runtime. satisfies checks the function against what rasti passes it:
// Compiles, but the argument is the MouseEvent: `props` is undefined at runtime.
onClick=${({ props }: ToggleComponent) => console.log(props.label)}
// Rejected (TS2339): `props` does not exist on `MouseEvent`.
onClick=${(({ props }) => console.log(props.label)) satisfies EventHandler<ToggleComponent, MouseEvent>}
Templates that call the component's own methods
When the template calls the component's own methods, as in (self) => self.renderItems(), Component<P, S, M> doesn't have them. Declare them in a class and call create on it. The new component extends that class, so the class is the type to use:
interface ListProps { items: string[]; handleSelect: (item: string) => void; }
class ListBase extends Component<ListProps> {
renderItems() {
return this.props.items.map((item) => this.html`<li>${item}</li>`);
}
select(ev: MouseEvent) {
const li = (ev.target as HTMLElement).closest('li');
if (li) this.props.handleSelect(li.textContent!);
}
}
const List = ListBase.create`
<ul onClick=${(function(ev) { this.select(ev); }) satisfies EventHandler<ListBase, MouseEvent>}>
${(self: ListBase) => self.renderItems()}
</ul>
`;
List.mount({ items: ['a', 'b'], handleSelect: (item) => console.log(item) }, document.body);
A subclass that defines template() itself, as in Components, needs neither the helpers nor create.
Functions passed to a child
For a function passed to a child, neither helper fits — its type comes from the child's prop. Type it against that prop's declared type (rasti can't connect the attribute to the child, since both live inside the template string):
// where the child was created with Component.create<ToggleAllProps>`...`
handleChange=${((checked) => model.toggleAll(checked)) satisfies ToggleAllProps['handleChange']}
A quoted value is the result of a function the parent runs, so what reaches the child is what that function returns. Annotate its return type with the child's prop: that checks the value, and it types the parameters of a callback returned by a thunk, which would otherwise be an implicit any (TS7006):
// where the child was created with Component.create<HeaderProps>`...`
handleAddTodo="${({ model }: AppComponent): HeaderProps['handleAddTodo'] => (title) => model!.addTodo(title)}"
satisfies on the returned callback does the same, ({ model }: AppComponent) => ((title) => model!.addTodo(title)) satisfies HeaderProps['handleAddTodo']; the return type keeps the whole contract in the signature.
Known limitations
- Template interpolation callbacks are
any(tagged form only). Functions inComponent.create`...`templates can't be inferred from the surrounding string — type them by where they sit in the template (see Typing template interpolations), or author the component as a subclass, where the template body is checked like any other method. - A component can't name its own type in its template (tagged form only).
InstanceType<typeof X>is circular there (TS7022). UseComponent<P, S, M>(see Typing template interpolations), or the classcreateis called on when the template calls its methods (see Templates that call the component's own methods). Model<A>instance keys require declaration merging. TypeScript can't addA's keys to aclass extends Model<A>automatically — see theinterface Todo extends TodoAttrs {}pattern above.- An attribute can't be named after a member of
Model. With declaration merging, an attribute such ason,getorsetconflicts with the member it shadows, and TypeScript reports it on the merged interface (TS2320). The shadowing breaks the model at runtime too, and development builds warn about it: rename the attribute, or prefix the generated properties withstatic attributePrefix. provide()is not checked against its keys. A computed key keeps the value's type, not theInjectionKey's, so the objectprovide()returns is typed as values by key and a value of the wrong shape compiles.injectis typed by the key.this.$()can returnnull. It mirrorsquerySelector, so handle the empty case (?.) and pass a type argument to narrow the element:this.$<HTMLInputElement>('input.edit')?.focus().this.$$()returns aNodeListOf<HTMLElement>(also narrowable).this.model/this.stateare optional. Both areundefinedunless provided, so guard (this.model?.foo) or assert (this.model!) when you know one was passed. Both accept a RastiModelor a model from another library (e.g. Backbone); Components subscribe tochangeevents automatically when the object exposeson/off.state/modelare raw generics,propsis not.this.propsis always aModelbuilt by rasti, so it's typedModel<P> & P(direct access toP's keys). Butstateandmodelcan be anything you provide — a RastiModel, a Backbone model, a store, or a plain object — so they stay the raw generic. To read a typedModelstate/model directly, define it as a named subclass with declaration merging and pass it as theS/Mgeneric (see theScoreboardexample above) — no casts needed.- Weak-type error on narrow props. If a component's
Phas no required keys and you pass only options not declared in it, TypeScript reports "has no properties in common" (weak-type check). Fix: declare those options inP— non-reserved options become props at runtime. - Instance fields set in
.extendhooks need predeclaration..extendinfers the instance type from the object's members only, so a field first assigned inonCreate(this.router = ...) isn't known. Predeclare it in the object:router: null as unknown as Router. For components with many instance fields, a class is usually cleaner than.extend:declare router: Routerin the class body, assigned inonCreate, andcreatecalled on the class (see Templates that call the component's own methods).