Learn how to implement type safety in your Kitten apps.

Topics covered

A little less magic, a little more type

A design goal of Kitten is to be easy to play with. Want to spin up a quick experiment or teach someone the basics of web development? Kitten should make that simple to do. Having magic globals like the kitten.html tagged template you saw earlier help with that.

However, for larger or longer-term projects where maintainability becomes an important consideration, you might want to implement type checking. Contrary to popular belief, you don’t have to use TypeScript or have a build process for this.

You can simply document your types using JSDoc and turn on type checking by adding a // @ts-check comment to the top of your JavaScript files. Any modern development environment that supports language intelligence for JavaScript via the TypeScript Language Server (e.g., Helix Editor, VSCodium, etc.) will pick them up and use them to provide you with static type checking, auto-completion, etc.

The question is, what do you do about Kitten’s magic globals?

(If you have type checking on, you will get errors like Cannot find name 'html' if you use them.)

The answer is, you can install and use the type-safe Kitten namespace package (@small-web/kitten) in your project.

Here’s how you’d update the Kitten Count example to do this:

  1. Create a miminal package.json file:

        "name": "kitten-count-typed",
        "type": "module"
  2. Install the package:

    npm install @small-web/kitten
  3. Import the strongly-typed kitten object (it’s the default export):

    // @ts-check
    import kitten from '@small-web/kitten'
    let /** number */ count = 1
    export default () => kitten.html`
      <h1>Kitten count</h1>

All the objects you find under the kitten namespace are also exported separately so, if you want to, you can also import just the objects you want. The following listing is thus equivalent to the one above:

// @ts-check
import { html } from '@small-web/kitten'

let /** number */ count = 1

export default () => html`
 <h1>Kitten count</h1>

Now that you know to use type safety and the @small-web/kitten module to create more maintainable Small Web apps, let’s take a little detour and look at Kitten’s Markdown support.

Next tutorial: Markdown