Type Definitions
Enhance offers a set of common type definitions that can be used with JSDoc comments to annotate critical parts of your Enhance project. These will help when writing custom elements, API middleware, and other critical pieces of an Enhance project.
Save @enhance/types to your development dependencies:
npm i -D @enhance/types
Usage Examples
If your editor supports auto-complete and error detection (like VS Code’s Intellisense) via commented types, you can indicate that a function adheres to a certain type.
Custom Element
Use the EnhanceElemFn
type when defining custom elements in /app/elements/. This will provide hinting for the argument passed to your function, including the html
function and state
object.
/**
* @type {import('@enhance/types').EnhanceElemFn}
*/
export default function TodoItem({
html,
state: { attrs }
}) {
const todoId = attrs['todo-id']
const completed = typeof attrs.completed === 'string'
return html`
<div class="flex">
<input
type="checkbox"
name="completed"
${completed ? 'checked' : ''}
/>
<slot></slot>
</div>
`
}
API Handler
In this case, mark this “Todos” API GET handler as the type EnhanceApiFn
and gain hinting for the request
and response
objects:
/** @type {import('@enhance/types').EnhanceApiFn} */
export async function get(request) {
console.log(`Handling ${request.path}...`)
const todos = [
{ title: 'todo 1'},
{ title: 'todo 2', completed: true },
]
const response = {
json: { todos }
}
return response
}
Note that the JSDoc comment can be a single line, but there cannot be an extra line between the comment and the method declaration.
Head Function
Your app’s Head function can also be typed with the request
argument and a return type of string
by adding EnhanceHeadFn
.
import { getLinkTag } from '@enhance/arc-plugin-styles/get-styles'
/** @type {import('@enhance/types').EnhanceHeadFn} */
export default function Head({ store, status, req, error }) {
const { path } = req
const title = `Todos — ${path}`
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>${title}</title>
${getLinkTag()}
</head>
`
}