Index āŗ 3. Type Safety
Learn how to implement type safety in your Kitten apps.
Topics covered
- JSDoc.
- TypeScript Language Server.
- The type-safe Kitten namespace package (@small-web/kitten).
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:
Create a miminal package.json file:
{ "name": "kitten-count-typed", "type": "module" }
Install the package:
npm install @small-web/kitten
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