Kitten

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>
      <p>${'šŸ±ļø'.repeat(count++)}</p>
    `
    

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>
 <p>${'šŸ±ļø'.repeat(count++)}</p>
`

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

Like this? Fund us!

Small Technology Foundation is a tiny, independent not-for-profit.

We exist in part thanks to patronage by people like you. If you share our vision and want to support our work, please become a patron or donate to us today and help us continue to exist.