HinMil — Hindley-Milner for JavaScriptHinMil is a VS Code extension that type-checks plain JavaScript. You write type
signatures in ordinary comments, and a Hindley-Milner inference engine checks
your code against them while you type. There is no build step and no
transpilation — the files stay plain
On top of the checker sit the editor features you would expect: hover types, diagnostics, completion, signature help, quick fixes, rename, and an outline view. The type system itself goes further than you might assume for a comment-based checker: records with row polymorphism, sum types, type classes with constraints, higher-kinded types, currying, overloading, and type narrowing. The sections below cover all of it. Table of Contents
Getting Started
That is the whole setup. The language server activates on the first JS file you open and checks as you type. Next steps, all optional:
Type AnnotationsAnnotations are written in comments directly above declarations, using
An annotation (or a directive) takes the whole comment line: text after the type is read as part of it. Put a remark on a line of its own, above:
Block comments work too, also over several lines (the annotation runs to the end of its paragraph, so a long signature can be wrapped):
Method AnnotationsUse
A constructor annotation declares the type, not its fields: give every
field you read through Named method and static annotations can also be placed above any declaration:
HoverHover over an identifier to see its inferred type. This works for variables
( The display style is configurable: DiagnosticsType errors show up in the editor as you type. The extension reports type mismatches, infinite types, missing record properties, unbound variables, syntax errors in annotations, unresolved imports, constraint violations, and curry arity problems — see the Diagnostic Codes Reference for the full list.
Every diagnostic category can be set to error, warning, information, hint, or off — see Configuration. AutocompletionCompletions are driven by the inferred types, so the suggestions after a dot
are the methods that actually exist for that type. This covers identifiers in
scope, methods and properties after
Each completion item shows the inferred type in the detail panel. Signature HelpWhen calling a function, the expected parameter types appear with the current parameter highlighted:
Works with multi-line calls and nested function invocations. Code ActionsQuick fixes available via the lightbulb menu or
Go to definition
Using HinMil without the built-in TypeScript extensionVS Code ships a built-in extension, TypeScript and JavaScript Language Features, that also analyses JavaScript. Next to HinMil it adds a second hover, its own (TypeScript) diagnostics and completions, and suggestions that do not know HM annotations. In a project that relies on HinMil you can switch it off for that workspace only:
Turn it back on the same way with Enable (Workspace). Good to know:
Find References & Rename
The engine is scope-aware, so shadowed variables in nested blocks are handled correctly. Document SymbolsThe outline view lists all top-level declarations with their inferred types:
Syntax HighlightingHM type annotations inside JS comments are syntax-highlighted automatically:
Can be toggled on/off via Sum TypesSum types (tagged unions, algebraic data types) are a core part of the
type system, and they need no directive. Any annotation whose right-hand
side is a
This registers the type constructor Variants and constructorsThe declaration names the variants, but the engine does not guess what
their constructors take — annotate each constructor explicitly. If one
is missing, the engine shows an info diagnostic with the exact
annotation to add (e.g. "Variant 'Just' is missing a constructor
annotation. Add:
Note that both Variant methodsA method annotated on the parent type ( Factory functions instead of classesClasses are not required. A capitalised factory function returning a record works the same way, and registered methods are offered as completions inside the returned record literal:
Multi-line declarations and complex fieldsVariant fields can be more than bare type variables: parenthesised type
applications and inline record groups are accepted. Long declarations
may span multiple comment lines, joined by a trailing or leading
Phantom variant parametersA type parameter that a variant does not use stays polymorphic when
that variant is produced.
Narrowing on variantsPredicates can narrow a value to a single variant via
Sum type declarations also show up in the document outline as enums with their variants as children. JSX & ReactJSX works out of the box in Every JSX expression
( Lowercase host elements ( React's own API is typed out of the box: the extension bundles signature
files for
A larger example — every annotation below is checked against the JSX usage:
What gets caught here:
Spread props type-check like object spreads ( Refs and the modern API are covered by the same bundled typings: the
Browser globals — The Fetch API is typed for every project (browser, node, workers) with no
configuration: Other React-ecosystem packages are one Runnable examples live in sample/jsx/ and sample/readme/jsx.jsx. Optional propsTwo conventions are supported, both fully checked:
Missing-prop diagnostics carry code Directives
|
| Type | Description |
|---|---|
Number |
JavaScript numbers |
String |
JavaScript strings |
Boolean |
true / false |
Null |
null |
Undefined |
undefined |
Void |
No return value |
Any |
A value nothing is known about (an import from an untyped package, globalThis); fits everywhere |
Numeric refinements in the style of Sanctuary — Integer, PositiveNumber,
NegativeNumber, NonZeroInteger, PositiveInteger, NonNegativeInteger,
FiniteNumber, ValidNumber, Float, Double, … — are Number to the
type checker. A numeric literal passed to such a parameter is checked
against the refinement (f (2.5) for f :: Integer -> … reports
'2.5' is not an integer); other values are not.
Calling Convention
JavaScript calls are tuple-applied: f(a, b) constructs Tuple[A, B]
and unifies it against the function parameter. So a multi-argument JS
function MUST be annotated in tuple form:
// For factory(a, b):
// factory :: (A, B) -> C
// For factory(a)(b) (curried):
// factory :: A -> B -> C
This is the single most common source of confusion when authoring sidecars — see Curry for how curried forms are detected.
Functions
// Single argument
// formatAmount :: Number -> String
const formatAmount = (n) => `€ ${n.toFixed(2)}`;
// Multiple arguments
// applyVat :: (Number, Number) -> Number
const applyVat = (amount, rate) => amount * (1 + rate);
// Higher-order
// map :: ((a -> b), [a]) -> [b]
const map = (fn, xs) => xs.map(fn);
An annotation is a promise the body must keep. Type variables are rigid inside the body: the caller chooses them, so the body may not pick one for them.
// second :: (a, b) -> b
const second = (x, y) => x;
// HM1003: 'second' has type '(a, b) -> a' but annotation expects '(a, b) -> b'
Type variables are scoped lexically, like generics: a letter in a nested annotation that also appears in the enclosing annotation is the same variable, so closure helpers can be annotated:
// keepWhere :: (a -> Boolean) -> [a] -> [a]
const keepWhere = (keep) => (items) => {
// The same `a` as in keepWhere:
// check :: a -> Boolean
const check = (item) => keep (item);
return items.filter (check);
};
A parameter with a JavaScript default value may be left out at a call site; the annotation names its type as usual:
// padLabel :: (String, Number, String) -> String
const padLabel = (label, width, fill = " ") => label.padEnd (width, fill);
padLabel ("Total", 10); // fine: `fill` has a default
Arrays & Tuples
// Arrays — homogeneous
// invoiceTotal :: [Number] -> Number
const invoiceTotal = (amounts) => amounts.reduce((a, b) => a + b, 0);
// Tuples — fixed-length, heterogeneous: one type per position
// formatLine :: [String, Number] -> String
const formatLine = (line) => `${line[0]}: ${line[1]}`;
formatLine (["Coffee", 3]); // fine
formatLine ([3, "Coffee"]); // Cannot unify 'Number' with 'String' (and back)
Do not confuse [A, B] (one tuple argument) with (A, B) (two arguments,
see Calling Convention).
Records & Row Polymorphism
// Record types with named fields
// customerLabel :: { name :: String, vatNumber :: String } -> String
const customerLabel = (customer) => `${customer.name} (${customer.vatNumber})`;
Records use structural typing — any object with matching fields satisfies the type.
Use ...rest to make a record open (extensible):
// pickName :: { name :: String, ...rest } -> String
const pickName = (o) => o.name;
// drop :: { x :: a, ...rest } -> { ...rest }
Open vs. open records unify their tails through a shared row variable; closed-vs-closed unification silently accepts extra caller fields for JS compatibility.
One exception catches typos: an object literal passed where a named closed record (an alias) is expected may not have fields the alias does not declare. That is reported as HM1010, with a "did you mean" hint when a declared field is close:
// Customer :: { name :: String, vatNumber :: String, email :: String | Undefined }
// customerLabel :: Customer -> String
const customerLabel = (c) => c.name;
customerLabel ({ name: "Acme", vatNumber: "NL001", emial: "info@acme.test" });
// HM1010 Unknown field 'emial' on argument; expected 'Customer' (did you mean 'email'?)
Values that are not literals (a record built elsewhere, a destructured parameter) and inline record types keep the lenient rule.
A computed key is the key's value: { ["currency"]: "EUR" } has a field
currency, a label variable makes a label field (k -> a -> { [k] :: a }),
and a key known only at runtime ({ [field]: value } with field :: String) gives a dictionary, Object String v, which Object.assign and
spreads merge as dictionaries. The level is
set with diagnostics.excessRecordFields.
Union & String-Literal Types
// Explicit union
// show :: Number | String -> String
const show = (x) => String(x);
// Automatically inferred from conditionals
const reference = Math.random() > 0.5 ? 2026001 : "draft";
// reference :: Number | String
// Singleton string-literal types
// statusLabel :: 'draft' | 'sent' | 'paid' -> String
const statusLabel = (s) => `status: ${s}`;
String literals in type position parse as TLabel (a singleton type).
At call sites a literal string must be one of the allowed values, and a
plain String does not fit a literal union (it could hold any text):
statusLabel ("paid"); // ok
statusLabel ("piad"); // HM1001: 'piad' is not one of 'draft' | 'paid' | 'sent'
// fromInput :: String -> String
const fromInput = (raw) => statusLabel (raw);
// HM1001: 'String' does not fit 'draft' | 'paid' | 'sent'
A literal assigned to a const keeps its literal type (const status = "sent" fits), and so does a ternary of literals (paid ? "paid" : "sent").
Unions have a direction. An argument must fit the parameter: every
member of a union argument has to be accepted by the parameter, so
Number | Undefined does not fit Number | Null. The other way round,
a function may return less than its annotation promises: a body that
returns String | Null satisfies -> String | Number | Null, but not
-> String (a member it does not declare).
// shown :: Number | Null -> String
const shown = (n) => n == null ? "-" : String (n);
// countLabel :: Number | Undefined -> String
const countLabel = (n) => shown (n);
// HM1001: Cannot unify 'Number | Undefined' with 'Null | Number'
Generics & Higher-Kinded Types
Lowercase identifiers are type variables (parametric polymorphism). Constraint-bound variables can stand for higher-kinded types:
// identity :: a -> a
const identity = (x) => x;
// fmap :: Functor f => ((a -> b), f a) -> f b
const fmap = (fn, fa) => fa.map(fn);
// chain :: Monad m => (a -> m b) -> m a -> m b
A constraint variable like f (declared in the constraint head) parses
greedily — it absorbs juxtaposed atoms (f a, m (Maybe a)). Plain
non-constraint vars only consume juxtaposition when followed by (...).
Two-parameter constructors work the same way: QueryTag p o,
Either e a, Map k v.
Label Polymorphism
A computed key — o[k], or destructuring ({ [k]: v }) => v — infers a
label variable (a separate sort from type vars) so accessors can be
polymorphic over field names:
// pluck :: (k, { [k] :: a, ...r }) -> a
const pluck = (k, o) => o[k];
pluck("x", { x: 1, y: 2 }); // k := 'x', a := Number
pluck("y", { y: "hi" }); // k := 'y', a := String
Type Aliases
Uppercase top-level names that don't return a constructor are treated as aliases. Free type variables are recorded and re-instantiated at each use site:
// LineItem :: { description :: String, quantity :: Number, unitPrice :: Number }
// Selector :: String | Prop a | Limit
Aliases expand at unification time with cycle detection, and they are
nominal: two aliases with the same fields are still different types, so a
Customer is not accepted where a Supplier is expected. A plain record
(an object literal, an unannotated value) fits any alias whose fields it has.
Properties & Private Members
Annotate non-method properties (no ~>) directly:
// Invoice#number :: String
// Invoice#lines :: [LineItem]
Private members (JS #name syntax) use a double ##:
// Counter :: () -> Counter
class Counter {
#count = 0;
// Counter##count :: Number
// Counter#tick :: Counter ~> () -> ()
tick() { this.#count++; }
}
Instance-Callable Values
Annotate values whose runtime values are themselves callable (parser tag functions, builder factories, etc.):
// The constructor:
// SQLTag :: a -> SQLTag a
// Calling an SQLTag instance:
// SQLTag() :: a -> Promise Error [b]
The Type() form lives in a separate namespace from the constructor;
hovering on a value of that type surfaces only the instance-callable
overloads.
Overloading
Repeating a top-level decl registers an additional call signature:
// total :: Invoice -> Number
// total :: [Invoice] -> Number
At each call site, the engine tries each branch in declaration order
and picks the first that unifies. A branch only fits when the
arguments fit its parameters in their direction:
a plain String does not take a 'asc' | 'desc' branch.
A union argument whose members fit different branches is resolved per member, as it runs, when the results agree:
// toPromise :: Promise e a -> Promise e a
// toPromise :: a -> Promise e a
const toPromise = (x) => x instanceof Promise ? x : Promise.resolve (x);
// Outcome :: { ok :: Boolean, field :: String }
// RuleResult :: Outcome | Promise Error Outcome
// passed :: RuleResult -> Promise Error Boolean
const passed = (result) => toPromise (result).then (outcome => outcome.ok);
// Outcome takes the second branch, the promise the first: Promise Error Outcome
Picked Projection
Picked Row Selectors is a built-in type constructor that projects a
row record at the call site. The introspect-style sidecar declares per-table
overloads like:
Organisation :: [OrganisationSelector] -> QueryTag p (Picked OrganisationRow OrganisationSelector)
When called with a literal-array argument, the LSP narrows Picked to
the actual selected fields. Method-shadows on the row type
(OrganisationRow#locations :: [LocationRow]) drive nested projection
for relations.
A nested query contributes what calling it returns, read off its type's instance-callable annotation, so a library controls the shape of a relation by how it types its query values:
QueryTag() :: p -> Promise e [o] // nested: a list relation
QueryOne() :: p -> Promise e (o | Null) // nested: one related row, or null
QueryExists() :: p -> Promise e Boolean // nested: a filter, adds no field
A callable whose result holds the row without an array (o, o | Null)
also receives the host's row type, like [o] does. A project override in
hm-types/<pkg>.hm may replace these callables, e.g. when the project runs
the library's queries through a runner that returns a task:
QueryTag() :: p -> RTask r Error [o]
Curry
To curry a function, you need a curry helper with the right signature. The LSP detects curry wrappers by their annotation pattern — a function that takes a tuple-param function and returns a curried version:
// curry :: ((a, b, ...) -> z) -> a -> b -> ... -> z
export const curry = fn => {
const curried = (...args) => {
if (args.length >= fn.length) return fn(...args);
return (...next) => curried(...args, ...next);
};
return curried;
};
Wrap any multi-param function with curry() to enable partial application:
// discountedTotal :: (Number, Number, Number) -> Number
const discountedTotal = (quantity, unitPrice, discountPct) =>
quantity * unitPrice * (1 - discountPct / 100);
const curriedTotal = curry(discountedTotal);
// curriedTotal :: Number -> Number -> Number -> Number
All partial application forms are then valid:
curriedTotal(2, 50, 10) // fully applied
curriedTotal(2)(50)(10) // fully curried
curriedTotal(2, 50)(10) // partial + apply
curriedTotal(2)(50, 10) // apply + partial
Note: Without wrapping in
curry(), a function with signature(a, b, c) -> dsimply expects all arguments at once. The LSP only generates curried overloads when it detects thecurry()call.
Pipe & Compose
The LSP supports variadic pipe and compose functions using spread tuple syntax in annotations. It validates that chained functions connect properly — the output of one must match the input of the next.
Pipe (left-to-right)
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => fns.reduce((acc, fn) => x => fn(acc(x)));
const invoiceLabel = pipe(
x => x * 1.21, // Number -> Number (apply VAT)
x => x.toFixed(2), // Number -> String (format)
x => `€ ${x}`, // String -> String (prefix)
);
// invoiceLabel :: Number -> String
The LSP verifies each link in the chain — if the output of one function doesn't match the input of the next, it reports a type error:
// withVat :: Number -> Number
const withVat = x => x * 1.21;
// format :: Number -> String
const format = x => x.toFixed(2);
const broken = pipe(format, withVat);
// Cannot unify 'Number' with 'String': format gives a String, withVat wants a Number
The links are checked against what is known about each function: an
unannotated lambda such as x => x * 1.21 is checked leniently (JavaScript
would coerce a String there), so give the steps signatures where the chain
matters.
Compose (right-to-left)
// compose :: ((y -> z), ..., (b -> c), (a -> b)) -> a -> z
const compose = (...fns) => fns.reduceRight((acc, fn) => x => fn(acc(x)));
const invoiceLabel = compose(
x => `€ ${x}`, // String -> String (prefix)
x => x.toFixed(2), // Number -> String (format)
x => x * 1.21, // Number -> Number (apply VAT)
);
// invoiceLabel :: Number -> String
The direction is detected automatically from the annotation — shared type variables between adjacent function positions determine whether the chain flows left-to-right (pipe) or right-to-left (compose).
Type Narrowing
Types are automatically narrowed inside conditional branches:
// typeof guards
if (typeof x === 'string') {
// x: String
}
// Null checks
if (x != null) {
// x: narrowed (null/undefined removed)
}
// Truthiness
if (x) {
// x: narrowed (null/undefined removed)
}
// ::narrow predicates
// ::narrow Number
// isNumber :: a -> Boolean
const isNumber = (x) => typeof x === 'number';
if (isNumber(value)) {
// value: Number
}
A guard that leaves the function narrows the rest of it, and so does a default that is assigned in the guard:
// Customer :: { name :: String, email :: String | Null }
// greeting :: Customer | Null -> String
const greeting = (customer) => {
if (!customer) return "Hello";
return "Hello " + customer.name; // customer: Customer
};
// pageSize :: Number | Null -> Boolean -> Number
const pageSize = (size) => (compact) => {
if (compact || size == null) return 10;
return size * 2; // size: Number
};
// displayName :: String | Null -> String
const displayName = (name) => {
if (name == null) name = "guest";
return name.toUpperCase (); // name: String
};
// emailOf :: Customer -> String
const emailOf = (customer) => {
if (customer.email == null) return "-";
return customer.email.toLowerCase (); // customer.email: String
};
Narrowing follows identifiers and member paths (customer.email), not
computed expressions: for orders[0].customer bind the value to a
const first.
Lookups that can miss
Map#get returns v | Undefined: the key may be absent. Three ways to
handle it:
// Fixture :: { id :: Number, team :: Number }
// rates :: Map String Number
const rates = new Map ([["NL", 0.21], ["BE", 0.21]]);
// 1. Check the result.
// vatOrZero :: String -> Number
const vatOrZero = (country) => rates.get (country) ?? 0;
// 2. Check the key first: after `has` on the same map and key, `get`
// cannot miss (also after `if (!m.has (k)) m.set (k, …);` and after
// `if (!m.has (k)) return …;`).
// vatOf :: String -> Number
const vatOf = (country) => rates.has (country) ? rates.get (country) : 0;
// groupByTeam :: [Fixture] -> Map Number [Fixture]
const groupByTeam = (fixtures) => {
const byTeam = new Map ();
fixtures.forEach (f => {
if (!byTeam.has (f.team)) byTeam.set (f.team, []);
byTeam.get (f.team).push (f);
});
return byTeam;
};
// 3. State it: you know the key is there (an invariant hinmil cannot see).
// dutchVat :: Number
const dutchVat = rates.get ("NL");
The third form works for any const whose value comes from a lookup —
a call, a member access or an await — that may give Undefined or
Null: the annotation may leave those out. The rest of the type must
still match (// dutchVat :: String is an error), and a value that is
undefined by construction (member ? 10 : undefined) is still
reported. The map and key of a has/get pair are compared as paths
(m, this.cache, state.byTeam; key, row.teamId, "NL"): a key
computed by a call (m.get (keyOf (row))) needs a const first.
Publishing types for an npm package
As a package author you have three independent ways to ship HM signatures
with your code. Pick whichever fits — or mix them. A consumer never has to
configure anything: the LSP discovers your signatures automatically when they
import your package.
1. Inline annotations (zero config)
Write // Name :: Type comments directly above your JS definitions.
No extra files, no package.json entry, no build step:
// node_modules/mylib/index.js
// limit :: Number -> Limit
exports.limit = (n) => ({ tag: 'limit', n });
// add :: Number -> Number -> Number
exports.add = (a) => (b) => a + b;
When a consumer does import { limit } from 'mylib', the LSP
BFS-walks your package starting from main / module, follows
import / export ... from / require edges, stays inside the
package root (no ../ escapes), and collects every inline
signature it finds. The walk is capped at 256 files per package.
Anything that works in source — ::constraint, sum type declarations,
type aliases, Type#method, Type() ::, ::types <pkg> chaining —
works inline too:
// node_modules/mylib/index.js
// ::constraint Runnable r { r :: (a -> r) | r }
// Pull in another lib's types too:
// ::types some-other-lib
// runIt :: Runnable r => r -> Limit r
exports.runIt = (r) => ({ tag: 'limit', r });
2. Sidecar .hm files
For authors who prefer to keep types out of the JS source, or version
them separately. Declare them under "hinmil" in package.json:
{
"name": "mylib",
"main": "index.js",
"hinmil": {
"sidecars": "./types.hm"
}
}
A sidecar contains the same declarations you would write in-source
(top-level signatures, Type#method, Type.static, Type() ::,
sum type declarations, ::constraint, type aliases, …) but without
the // comment prefix — it's pure HM source. In a .hm file //
starts a comment, on a line of its own or after a declaration
(Status :: 'open' | 'paid' // as the provider sends it); /* … */
blocks are comments too. Directives are written bare as well
(::types other-lib, ::constraint …): a // ::types … line in a
.hm file is a comment.
Multiple sidecars are supported; later entries override earlier ones for both value exports and type aliases:
{
"hinmil": {
"sidecars": [
"./sqlkit.hm",
"../.sqlkit/client/index.hm"
]
}
}
Sidecar files are watched: edits trigger transitive cache invalidation so downstream files re-check immediately.
3. Package globals
For symbols that should be in scope for every file in a consumer
project — type aliases, ambient constraints, shared kinds — without
each consumer file needing a // ::types directive. This is a config
key, not to be confused with the ::global directive
(which registers methods/statics on types): "globals" makes a whole
declaration file ambient. Declare under the same "hinmil" block:
{
"hinmil": {
"sidecars": "./sqlkit.hm",
"globals": ["./sqlkit.hm"]
}
}
"globals" must be an array (a bare string is rejected with a
warning). Every consumer file in the workspace automatically gets
these declarations merged into its environment.
Merge order
When the same name appears in multiple sources, later wins:
bundled builtin < inline < sidecar < companion package < project-local override
A bundled builtin is a signature file shipped with the extension itself
(hm-types-builtin/): react and react-dom, and the
Node modules assert, buffer, child_process, crypto, fs, http,
os, path, url and zlib (node:fs is the same as fs). It is the
weakest layer, and any package backed by one is open-world: importing a
name no layer declares binds it to Any instead of erroring, so an
outdated bundle can never be worse than no typings. A Node module without
a bundled file (for example readline) gives HM3003; add a project stub
in hm-types/<module>.hm (methods as Type#method :: Type ~> …).
A built-in type that has no Name :: declaration (such as ReactElement)
is documented in its bundled file with an anchor line // ::builtin Name;
go to definition on the type name jumps there.
A companion package is an @hm/<pkg> package that ships sidecars
for a package that has none itself (like @types/* in the TypeScript
world): lodash → @hm/lodash, @scope/pkg → @hm/scope__pkg. It
is only consulted when the package provides neither inline annotations
nor its own sidecar.
So a project can always shadow a published signature by declaring it locally, a sidecar shadows inline annotations, and inline is the fallback when nothing else is declared.
Cross-package chaining
A .js or .hm source can pull in another package's types
explicitly with // ::types:
// A bare specifier: recurse into that package's scan.
// ::types other-pkg
// A sibling JS file, and a sibling sidecar:
// ::types ./helper.js
// ::types ./types.hm
This is useful when your signatures reference types declared in a dependency. Results are cached per package root, so transitive chains don't re-scan on every import.
Using a typed npm package (consumer side)
There is nothing to configure. Install and import:
const { limit, add } = require('mylib');
const x = add(1)(2); // hover shows: Number
const y = limit('hi'); // diagnostic: expected Number, got String
The LSP resolves mylib via Node's normal node_modules lookup,
applies sidecar (if any), falls back to inline scan, merges globals,
and caches the result per package root. Subsequent imports of the
same package are free.
The package's methods (Type#method in its sidecar or inline annotations)
come along with the import: makeCart ().count () is typed as soon as
makeCart is imported. A ::types directive is only needed for type-only
use — a file that names the package's types in its annotations but imports
nothing from it:
// ::types sqlkit
// queryOf :: SqlKit -> String
const queryOf = (kit) => kit.toString ();
When signatures don't show up
A few common gotchas:
- No
main/moduleinpackage.json— the inline scan falls back toindex.{js,mjs,cjs}. If that's also absent, no signatures. - Symlinked / linked package in dev (
npm link,pnpm) — usually works, but cache may go stale after edits insidenode_modules. Restart the LSP if you're not seeing fresh signatures. - Annotation lives outside the package root — the BFS won't follow
../escapes. Use// ::types <relative-or-bare>to chain explicitly. "globals"config key declared as a string — ignored, with a warning. Always an array (see Package globals).- Re-export chain >256 files — scan cap is hit; declare a sidecar for the affected names.
Built-in Method Types
The LSP ships type definitions for the standard JavaScript built-ins: Array,
String, Object, Number, BigInt, RegExp, Promise, Map, Set, Math, Date
(including Date.UTC and the setUTC… setters), JSON, Intl formatters,
URLSearchParams, AbortController/AbortSignal, the timers
(setTimeout, … — their ids are TimeoutId/IntervalId) and, with
hinmil.dom.globalTypes, the browser DOM. globalThis is Any. Node
modules are typed through the bundled files listed under
Merge order. The tables below show the most common methods —
hover any method call to see the exact signature.
Optional trailing parameters are written as | Undefined. A callback
result written t may be anything: filter, find, some, every,
findIndex and findLast(Index) read it as truthy/falsy, so
orders.filter (o => o.paidAt) needs no Boolean. Awaited b is b
with a returned promise unwrapped (then (x => fetchNext (x)) gives
Promise e Next, not a promise of a promise).
Array Methods
| Method | Type |
|---|---|
map |
((a, Number, [a]) -> b) -> [b] |
filter |
((a, Number, [a]) -> t) -> [a] |
reduce |
((b, a, Number, [a]) -> b, b \| Undefined) -> b |
find |
((a, Number, [a]) -> t) -> a |
some |
((a, Number, [a]) -> t) -> Boolean |
every |
((a, Number, [a]) -> t) -> Boolean |
flatMap |
((a, Number, [a]) -> [b]) -> [b] |
forEach |
((a, Number, [a]) -> b) -> () |
concat |
[a] ~> ([b] \| b) -> [a \| b] |
includes |
(a, Number \| Undefined) -> Boolean |
indexOf |
(a, Number \| Undefined) -> Number |
slice |
(Number \| Undefined, Number \| Undefined) -> [a] |
join |
(String \| Undefined) -> String |
reverse |
[a] |
length |
Number (property) |
| ... | and more |
String Methods
| Method | Type |
|---|---|
charAt |
(Number \| Undefined) -> String |
includes |
(String, Number \| Undefined) -> Boolean |
indexOf |
(String, Number \| Undefined) -> Number |
split |
(String \| RegExp \| Undefined, Number \| Undefined) -> [String] |
slice |
(Number \| Undefined, Number \| Undefined) -> String |
startsWith |
(String, Number \| Undefined) -> Boolean |
replace |
(RegExp \| String, String) -> String |
padStart |
(Number, String \| Undefined) -> String |
toLowerCase |
String |
toUpperCase |
String |
trim |
String |
length |
Number (property) |
| ... | and more |
Object Static Methods
| Method | Type |
|---|---|
Object.keys |
a -> [String] |
Object.values |
a -> [b] |
Object.entries |
a -> [[b]] |
Object.fromEntries |
[[b]] -> a |
Object.assign |
(a, b) -> { ...a, ...b } (overloads for 1–4 arguments; dictionaries Object k a merge to Object k (a ∪ b)) |
Object.freeze |
a -> a |
Object.is |
(a, a) -> Boolean |
Object.hasOwn |
(a, String) -> Boolean |
| ... | and more |
These stay deliberately loose — objects flow through them without forcing a specific record shape.
Promise Methods
Promises are typed as Promise e a — error type first, value type second.
| Method | Type |
|---|---|
then |
(a -> b, (e -> c) \| Undefined) -> Promise e (Awaited b) |
catch |
(e -> b) -> Promise e b |
finally |
(() -> ()) -> Promise e a |
Promise.resolve |
a -> Promise e a |
Promise.reject |
e -> Promise e a |
Promise.all |
[Promise e a] -> Promise e [a] |
Promise.race |
[Promise e a] -> Promise e a |
Promise.allSettled |
[Promise e a] -> Promise e [a] |
Promise.any |
[Promise e a] -> Promise e a |
Map Methods
Typed as Map k v.
| Method | Type |
|---|---|
get |
k -> (v \| Undefined) — see lookups that can miss |
set |
(k, v) -> Map k v |
has |
k -> Boolean |
delete |
k -> Boolean |
forEach |
((v, k, Map k v) -> b) -> () |
keys |
[k] |
values |
[v] |
entries |
[(k, v)] |
size |
Number (property) |
Map.groupBy |
([a], (a -> k)) -> Map k [a] |
Set Methods
Typed as Set a, including the newer set-operation methods.
| Method | Type |
|---|---|
add |
a -> Set a |
has |
a -> Boolean |
delete |
a -> Boolean |
forEach |
((a, a, Set a) -> b) -> () |
values / keys |
[a] |
entries |
[(a, a)] |
union / intersection / difference / symmetricDifference |
Set a -> Set a |
isSubsetOf / isSupersetOf / isDisjointFrom |
Set a -> Boolean |
size |
Number (property) |
Configuration
HinMil reads settings from two places:
- Editor settings — the
hinmil.*namespace in VS Code (Settings UI orsettings.json). - Project file — a
"settings"key in the project config (package.json#hinmil,hinmil.config.jsonorhinmil.config.js). Project-file settings override editor settings, so a repository can pin its own diagnostics policy for every contributor.
Diagnostic categories share a uniform level enum — off, hint, information, warning, error — where off disables the category entirely.
Configuration per folder (monorepos)
A file uses the nearest folder above it that has HinMil configuration
(hinmil.config.json, hinmil.config.js or a "hinmil" key in
package.json), up to the workspace root (or the CLI's --project).
Each such folder is its own project scope with its own globals,
typesDir, overrides and settings, so a server/ and a client/
application can each declare their own Order type:
shop/
├── hinmil.config.json { } ← workspace root (the editor needs one here)
├── server/
│ ├── hinmil.config.json { "globals": ["./globals.hm"] }
│ ├── globals.hm Order :: { id :: String, total :: Number }
│ └── src/orders.js ← uses server/globals.hm
└── client/
├── hinmil.config.json { "globals": ["./globals.hm"] }
├── globals.hm Order :: { id :: String, lines :: [String] }
└── src/summary.js ← uses client/globals.hm
Multi-root workspaces. Every folder of a multi-root workspace is a
project of its own, with its own configuration, globals, file selection
(files) and project-file settings, and folders can be added or removed
while the editor runs. A folder with "enable": false in its
configuration is skipped: its files get no diagnostics, hover or other
answers. Settings that apply to the server as a whole (the diagnostics
debounce and the dom group) follow the first folder that is checked.
Within one workspace folder, the file selection (files) and the
project-file settings come from the editor and that folder's root
configuration; a configuration in a subfolder contributes its globals,
typesDir and overrides. Paths in a configuration (globals,
typesDir) are relative to its own folder. With hinmil.requiresConfig,
the language server starts only when a workspace folder itself has
configuration (an empty {} is enough), and only such folders are
checked.
Enabling / disabling the language server
Once the extension is installed it activates for every JavaScript file. Two settings and one project-config key control whether the language server actually runs:
hinmil.enable(editor setting, defaulttrue) — the master switch. Put"hinmil.enable": falsein a project's.vscode/settings.jsonto turn HinMil off for that project while keeping it on everywhere else, or set it in your user settings to disable it globally."enable": false(project config) — opt a repository out from within the repository itself, without touching editor settings. Works inhinmil.config.json,hinmil.config.js, and the"hinmil"key ofpackage.json:// hinmil.config.json (or package.json → "hinmil": { "enable": false }) { "enable": false }hinmil.requiresConfig(editor setting, defaultfalse) — opt-in mode. Whentrue, the server only starts if at least one workspace folder has explicit HinMil project configuration at its root: ahinmil.config.json/hinmil.config.jsfile or a"hinmil"key inpackage.json(a configuration only in a subfolder does not count). In a multi-root workspace the folders without such configuration are then not checked. Set this once in your user settings and HinMil stays dormant in every project that hasn't opted in — no per-project settings needed.
All of these take effect immediately (no reload): toggling them starts or stops the server, and config-file changes are picked up the moment they happen. hinmil.enable: false wins over everything, including the restart command. Note that syntax highlighting of HM annotations is controlled separately by hinmil.syntaxHighlighting.enabled.
| Setting | Default | Description |
|---|---|---|
hinmil.enable |
true |
Run the language server at all. Set to false in a workspace's .vscode/settings.json — or "enable": false in the project config file — to disable HinMil for one project only |
hinmil.requiresConfig |
false |
Only start the language server when a workspace folder contains explicit HinMil project configuration (see below) |
hinmil.files.extensions |
.js, .jsx, .mjs, .cjs, .hm |
Source extensions HinMil checks (see Command-Line Checker); also settable as files in the project config |
hinmil.files.include |
**/* |
Globs of files to check |
hinmil.files.exclude |
node_modules, .git, dist, build, coverage |
Globs of files not to check on their own (still inferred when imported). A list you set replaces the defaults |
hinmil.diagnostics.enabled |
true |
Master switch for all diagnostics |
hinmil.diagnostics.typeErrors |
error |
Level for type mismatch / unification errors (codes 1001–1004, 1009, 7001) |
hinmil.diagnostics.unknownPropertyAccess |
error |
Level for property access on unknown or unconstrained types (codes 1005, 1006) |
hinmil.diagnostics.missingRecordFields |
error |
Level for record values missing required fields (code 1008) |
hinmil.diagnostics.excessRecordFields |
error |
Level for object-literal arguments with fields their named record type does not declare (code 1010) |
hinmil.diagnostics.annotationNarrowing |
error |
Reserved: level for code 2009, which no check emits at the moment (an annotation narrower than the inferred union is reported as 1003, or allowed for a lookup). Kept so existing configurations stay valid |
hinmil.diagnostics.missingSignatures |
information |
Level for functions without an HM annotation |
hinmil.diagnostics.missingVariableSignatures |
off |
Level for variables without an HM annotation |
hinmil.diagnostics.trustAnnotations |
off |
Trust user annotations and suppress diagnostics inside trusted bodies — see levels below |
hinmil.diagnostics.debounceMs |
500 |
Delay (ms) before publishing diagnostics after an edit. Only affects diagnostics — hover, completion and signature help respond immediately |
hinmil.display.typeVariables |
pretty |
Type-variable display: pretty (a, b, c) or raw (internal names) |
hinmil.hover.enabled |
true |
Show inferred types on hover |
hinmil.completion.enabled |
true |
Enable autocompletion |
hinmil.completion.autoImports |
true |
Suggest exports from other workspace files with an automatic import edit |
hinmil.signatureHelp.enabled |
true |
Show parameter info on function calls |
hinmil.navigation.definitions |
auto |
Go to definition for module paths, imported names and local names (see Go to definition): auto (only when VS Code's built-in TypeScript/JavaScript extension is not active), always, off |
hinmil.dom.globalTypes |
true |
Typed browser globals (document → Document, …) with IntelliSense on the compact DOM catalogue; DOM type names become valid in annotations. Off reverts the globals to Any |
hinmil.dom.strictNulls |
false |
DOM lookups that can miss (getElementById, querySelector, getAttribute, getItem, …) return T \| Null |
hinmil.syntaxHighlighting.enabled |
true |
Highlight HM annotations in comments (requires reload) |
hinmil.trace.server |
off |
LSP message tracing between VS Code and the server (off, messages, verbose) |
Project-file settings
The project config has these top-level keys: enable (opt the project out, see above), globals, overrides, typesDir, files (the file selection, see Command-Line Checker) and settings. Inside settings go the setting groups of the table above — diagnostics, display, hover, completion, signatureHelp, navigation, dom — without the hinmil. prefix. requiresConfig, syntaxHighlighting and trace are editor-only. Project-file settings win over editor settings and are hot-reloaded when the file changes:
// package.json
{
"hinmil": {
"globals": ["./globals.hm"],
"settings": {
"diagnostics": { "typeErrors": "warning", "missingSignatures": "off" },
"display": { "typeVariables": "raw" }
}
}
}
The same "settings" key works in a standalone hinmil.config.json or hinmil.config.js (module.exports = { settings: { … } }).
trustAnnotations levels
Cumulative tiers — each level includes everything the previous one does.
missingSignatures / missingVariableSignatures are orthogonal and remain
active on every level.
| Level | Behaviour |
|---|---|
"off" (default) |
Full validation. Annotation-vs-inferred mismatches and every in-body type error are reported. |
"signatures" |
Trust signatures: drop annotation mismatches (code 1003) so a :: annotation is treated as ground truth, but body type errors are still surfaced. |
"annotated-bodies" |
Above, plus suppress every diagnostic whose range falls inside a binding that carries a :: annotation. Use when annotated bodies are considered "audited" and you only want errors in unannotated code. |
"all-bodies" |
Above, plus suppress diagnostics inside every top-level binding (annotated or not). Only diagnostics outside binding bodies (e.g. top-level expression statements, missing-signature notices) remain. |
Any unrecognized value falls back to "off" with a warning.
Command-Line Checker
Install the npm CLI as a development dependency and run the same project-aware checker outside the editor:
npm install --save-dev hinmil
npx hinmil .
hinmil [paths...] [options]
--project <directory> Project root (default: current directory)
--config <file> Explicit hinmil JSON or JS config
--format stylish|json Human-readable or machine-readable output
--ext <extension> Add an extension (repeatable; e.g. --ext .vue)
--help, -h Show usage
--version, -v Show the package version
With no paths the project root is scanned. File selection is loaded before discovery. The built-in extensions are .js, .jsx, .mjs, .cjs, and .hm; --ext adds to (rather than replaces) the effective list. Explicit file and directory arguments obey the same extension/include/exclude filters as discovered files.
Configure selection in package.json#hinmil, hinmil.config.json, or hinmil.config.js:
{
"files": {
"extensions": [".js", ".jsx", ".mjs", ".cjs", ".hm", ".custom"],
"include": ["src/**", "types/**"],
"exclude": ["**/*.generated.js", "**/vendor/**"]
}
}
The precedence is built-in defaults → VS Code hinmil.files.* → project files; each specified array replaces the lower layer. So an exclude of your own must repeat the defaults you still want (**/node_modules/**, **/.git/**, **/dist/**, **/build/**, **/coverage/**). CLI --ext additions apply last. An explicitly empty include array selects no files. Exclusion suppresses only standalone diagnostics: an excluded module imported by a selected file is still parsed and inferred. Discovery visits each real directory once and follows symlinked directories only when they stay inside the project root.
For custom source extensions in VS Code, map them to JavaScript so the editor sends the document with the right language id:
{
"files.associations": { "*.custom": "javascript" },
"hinmil.files.extensions": [".js", ".jsx", ".mjs", ".cjs", ".hm", ".custom"]
}
Without --config, each file is checked with the configuration of its nearest folder (see Configuration per folder); within one folder, discovery uses package.json#hinmil, then hinmil.config.js, then hinmil.config.json. An explicit --config applies to every file. The file selection (files) always comes from the project root (or --config). JavaScript config is limited to a JSON-compatible module.exports object and is not executed. Exit status is 0 without error diagnostics, 1 with errors, and 2 for argument/config/input failures.
Use --format json for machine-readable output. It emits one object containing project, the ordered checkedFiles, configuration warnings, and ordered diagnostics; each diagnostic contains its absolute file, severity, HM code, message, and zero-based LSP range. A typical CI script can rely directly on the exit status:
{
"scripts": {
"typecheck:hm": "hinmil --format json"
}
}
npm run typecheck:hm
Diagnostic Codes Reference
| Code | Category | Description |
|---|---|---|
| 1001 | Type Error | Type mismatch — cannot unify types |
| 1002 | Type Error | Infinite type detected |
| 1003 | Type Error | Annotation mismatch |
| 1004 | Type Error | Return type doesn't match annotation |
| 1005 | Type Error | Missing property on record |
| 1006 | Type Error | Unconstrained property access on type variable |
| 1007 | Type Error | Unbound variable |
| 1008 | Type Error | Record value missing required fields |
| 1009 | Type Error | Value is not callable |
| 1010 | Type Error | Object literal has a field its named record type (alias) does not declare — usually a typo in an optional field (form for from :: Date \| Undefined); comes with a "did you mean" hint |
| 2001 | Annotation | Invalid annotation syntax |
| 2002 | Annotation | Declaration name doesn't match annotation name |
| 2003 | Annotation | Method name mismatch |
| 2004 | Annotation | Unknown type constructor |
| 2005 | Annotation | Using variant method instead of parent method |
| 2006 | Annotation | Method type mismatch |
| 2007 | Annotation | Nameless annotation (:: Type) placed on a named declaration |
| 2008 | Annotation | Type constructor applied to the wrong number of arguments |
| 2009 | Annotation | Reserved (not emitted at the moment; see annotationNarrowing) |
| 2010 | Annotation | Missing runtime argument for a TypeRep parameter |
| 2011 | Annotation | Bare type variable used as a value annotation |
| 2012 | Annotation | Method annotation on a bare value type |
| 2013 | Annotation | Instance-callable annotation (Type() ::) on a type with no constructor |
| 2014 | Annotation | Method or static annotation on a type with no constructor |
| 2015 | Annotation | Invalid ::narrow directive |
| 3001 | Module | Missing export |
| 3002 | Module | Unresolved ::types path |
| 3003 | Module | Unresolved import |
| 3004 | Module | Duplicate import |
| 3005 | Module | Circular import |
| 4001 | Constraint | Unknown constraint name |
| 4002 | Constraint | Constraint violation |
| 4003 | Constraint | Invalid constraint definition |
| 4004 | Constraint | Constraint kind mismatch (e.g. concrete type where a container is required) |
| 5001 | Curry | Curry arity mismatch |
| 5002 | Curry | Curry type error |
| 5003 | Curry | Over-application of curried function |
| 5004 | Curry | Fan-out arity mismatch |
| 6001 | Info | Missing annotation (informational) |
| 6002 | Info | Sum type variant missing an annotated method implementation |
| 7001 | Relation | Invalid table relation / picked projection |
| 9001 | Parse | Source code parse error |
Example: Full Workflow
A small module that combines annotations, a sum type, a constraint, and narrowing:
// Maybe :: Just a | Nothing
class Just {
// Just :: a -> Maybe a
constructor(value) { this.value = value; }
// Maybe#map :: Maybe a ~> (a -> b) -> Maybe b
map(fn) { return new Just(fn(this.value)); }
}
// Nothing :: Maybe a
class Nothing {
map(_fn) { return new Nothing(); }
}
// ::constraint Functor f { f :: { map :: f a ~> (a -> b) -> f b } }
// fmap :: Functor f => ((a -> b), f a) -> f b
const fmap = (fn, f) => f.map(fn);
// findDiscount :: Number -> Maybe Number
const findDiscount = (total) =>
total < 500 ? new Nothing() : new Just(total * 0.05);
// discounts :: [Number] -> [Maybe Number]
const discounts = (totals) => totals.map(findDiscount);
// ::narrow Number
// isNumber :: a -> Boolean
const isNumber = (x) => typeof x === 'number';
// formatReference :: (Number | String) -> String
const formatReference = (x) => {
if (isNumber(x)) {
return x.toFixed(0); // x: Number (narrowed)
}
return x; // x: String (narrowed)
};
License
MIT — see LICENSE.