Type Annotations
GocciaScript's TypeScript-compatible type syntax: the TC39 Type Annotations proposal, the --strict-types runtime extension, and the parsing rules that govern them.
Executive Summary
- Types as comments by default — Supported annotations follow the TC39 Type Annotations proposal's types-as-comments model and have no runtime effect
- Optional enforcement —
--strict-typeschecks supported annotations at runtime; it is a runtime contract, not a static structural checker such astsc - Extension decides
<— A leading<is read as JSX or as a type parameter list by file extension, modeled on TypeScript with GocciaScript-specific extension rules (JSX is also recognized in.jsand.mjs, and never in.tsor.mts) - Restricted
!productions — Definite assignment and non-null assertions must sit on the same line as their operand, so ASI code keeps its usual meaning - Bounded surface — Namespaces, parameter properties, angle-bracket assertions, and class-field definite assignment are deliberately unsupported
The annotation surface is part of GocciaScript's language profile; see Language for the ECMAScript baseline it sits on and Language Tables for the proposal-status matrix.
Proposal and Runtime Model
GocciaScript implements the TC39 Type Annotations proposal. Supported annotations follow its types-as-comments model and have no runtime effect by default. Each annotation's text is kept on its AST node in a normalized form (tokens joined by spaces, a template literal type as one escaped token) that --strict-types reads; the original spelling is in the source ranges goccia:ast reports.
GocciaScript runtime extension — pass --strict-types (or set "strict-types": true in goccia.json) to enforce supported annotations at runtime. Annotated variables, function parameters, and literal-inferred types are checked on initial value and on every assignment, ++ and -- included; incompatible values throw TypeError. Two gaps remain: a store the compiler reaches before the binding's declaration, such as one in a closure created earlier, is not checked (#2178), and an update inside a var initializer can leave its result in that var, the updated binding included, when its check throws (#2179). An annotation is enforced only where every value its type admits passes the check, read from the type's outermost form: number, string and boolean check the primitive, and object, array and tuple types (T[], readonly T[], [A, B]) and function and constructor types reject a primitive. Every other form stays unenforced: unions (string | number, a leading | included), intersections, any, unknown, indexed access (N["kind"]), conditional and mapped types, keyof, literal and template literal types, object type literals, and every name, Array<T>, Map<K, V>, Promise<T>, Function and Object included, since a type alias, interface or import can rebind a name. The checks take the primitive wrappers' interfaces (Number, String, Boolean, Symbol, BigInt) as the standard library declares them: a program that augments one to extend an array or function type can have a primitive refused by an array or function type check. A declaration without an initializer is not checked: an annotated let or var holds undefined until it is assigned, and operators on it give their usual result (let n: number; then n + 1 is NaN). A var also holds undefined before its declaration runs, initializer or not, so a var read where its declaration was skipped gives the same result. A rest parameter's array is not checked against its annotation on entry, so (...xs: number) => xs + 1 concatenates, while an assignment to it, xs += 1 included, is checked. This optional runtime contract is not a replacement for a static structural checker such as tsc.
An unannotated let takes an inferred type from the syntactic form of its initializer alone, and only from these forms:
| Initializer | Inferred type |
|---|---|
| Number, string, or boolean literal | number, string, or boolean |
| Template literal, with or without substitutions | string |
Object literal, array literal, new expression, arrow function, or function expression | object (any non-primitive value) |
Every other initializer leaves the binding untyped, whatever the engine could work out about its value: an identifier, a call, an operator expression (including a negated number such as -1), a BigInt literal, null, or undefined. The bytecode compiler may still infer a Number for such a binding to choose typed instructions, but only when it proves that every value the binding can hold is a Number. An assignment of any other value defeats the proof, so total = "text" above stays allowed, and the inference is never enforced (Compiler Type Inference).
const base = 16;let count = 1; // inferred number: count = "text" throws TypeErrorlet total = base + 1; // untyped: total = "text" is allowed
Supported Syntax
// Variable type annotationslet x: number = 42;const name: string = "hello";let value: string | number = "test";// Parameter type annotations (simple, optional, rest, destructuring)const add = (a: number, b: number): number => a + b;const greet = (name?: string) => name === undefined ? "hi" : "hi " + name;const sum = (...nums: number[]) => nums.reduce((a, b) => a + b, 0);const first = ({ name, age }: { name: string, age: number }) => name;// Return type annotations, including unions and intersections of object typesconst double = (x: number): number => x * 2;class Registry {lookup(flag: boolean): string | { code: number } { return flag ? "ok" : { code: 7 }; }build(): { name: string } & { size: number } { return { name: "box", size: 2 }; }}// Template literal types, also in call and constructor type argumentsconst id: `id-${number}` = "id-42";const also = "id-42" as `id-${number}`;const user = load<`user-${string}`>(key);// Definite assignment assertions (require an annotation, forbid an initializer)let pending!: number;pending = 5;// Non-null assertions (postfix !, erased — the chain continues unchanged)const nonNull = { v: "x" };nonNull.v!.length;const firstY = [{ y: 1 }][0]!.y;// Generic arrow function expressions, async ones includedconst identity = <T,>(v: T): T => v;const withDefault = <T = string,>(v: T): T => v;const load = async <T,>(read: () => Promise<T>): Promise<T> => read();// A `this` parameter types `this`; it is not a parameter at run time, so// `Counter.prototype.total.length` is 1. Overload signatures (erased) are a// function or method header with no body, ended by `;` or, under ASI, a line// break; the implementation keeps its own parameters, so// `Counter.prototype.pick.length` is 1. Both also// work on `function` declarations under `--compat-function`.class Counter {base = 2;total(this: Counter, extra: number) { return this.base + extra; }pick(text: string): string;pick(count: number): number;pick(value: string | number) { return value; }}// Type and interface declarations (skipped entirely)type Point = { x: number, y: number };interface Animal { name: string; speak(): string; }// import type / export type (skipped entirely)import type { Foo } from './types.js';export type { Bar };// `type` is a legal default binding, so these are ordinary value imports that// bind `type`. After `import type`, a binding, `{` or `*` makes the import// type-only; `from` before a module string, or `,`, makes `type` the binding.import type from './x.js';import type, { y } from './x.js';import type, * as ns from './x.js';// Mixed type/value named bindings keep runtime imports/exports for value bindingsimport { parseSourceFile, type SourceFile } from "./parser.js";export { value, type ValueShape };// export interface declarations are skipped entirelyexport interface Serializable {toJSON(): string;}// Ambient declarations (skipped entirely): `declare` before a variable,// function, class, enum, module, `global` or namespace on the same line.// They bind nothing at run time; `declare` alone is still an identifier.declare const process: { env: Record<string, string | undefined> };declare module "virtual:assets" { const url: string; export default url; }declare global { interface Window { app: unknown } }export declare function helper(name: string): void;// Runtime-erased as, satisfies, and generic constructor syntaxconst asserted = 42 as number;const colors = ["red", "green"] as const satisfies Array<string>;const names = new Map<string, string>();// Class annotations: field types, generics, implements, access modifiersclass Box<T> implements Container {public value: T;private label?: string;readonly id: number = 1;constructor(value: T) { this.value = value; }get(): T { return this.value; }}// Catch parameter type annotationtry { throw new Error("oops"); } catch (e: Error) { }
A type-level statement erased this way still has a kind of its own in goccia:ast, so a tool reading the source can tell it from an empty statement.
Angle Brackets and JSX
A leading < is ambiguous: it can open a JSX element or a type parameter list. GocciaScript resolves this by file extension — modeled on TypeScript's .ts/.mts versus .tsx rule, with GocciaScript-specific extensions: JSX is also recognized (with a warning) in .js and .mjs sources.
-
.ts,.mts— JSX is never recognised, so<is always type syntax. Generic function type annotations parse here, as does every generic arrow form — including the bare<T>the JSX extensions cannot take. A generic arrow can beasync:async <T>(v: T) => vhere, andasync <T,>(v: T) => vin the JSX extensions below.const identity: <T>(x: T) => T = (x) => x;const wrap = <T>(v: T): T[] => [v];const idOf = <T extends { id: number }>(v: T): number => v.id;A
<after a callee opens call or constructor type arguments only where TypeScript reads it that way: the list closes before(or a template, and holds nothing that cannot be type syntax. Soa < b > (c)is a generic call here, whilea < f() > (c)anda < `x${b + 1}` > (c)stay comparisons. A list with a template literal type that has substitutions, such as`user-${string}`, is erased only when the whole list reads as types: names with type arguments, literals,keyof,typeof,readonly,infer, unions, intersections, conditional types, indexed access, arrays, tuples, object types of property signatures, function, generic function and constructor types, import types and templates whose substitutions are such types. Any other list with a template keeps the comparison reading, even where TypeScript would read a rarer type form: a mapped type, a constrainedinfer U extends T, a destructured or computed name, an import type with attributes, a negative number beside the template at the top of the list, or a generic function type written straight after the list's<(f<<T>() => T>, which lexes as a shift; writef< <T>() => T>). A typed tag afternew,new tag<T>`text`, is not read either. -
.js,.jsx,.tsx,.mjs— JSX is recognised, so a bare<T>or<T extends U>is read as a JSX element. Generic arrows still parse when the type parameter list cannot be mistaken for a tag, which means a trailing comma, a default, or more than one parameter:const identity = <T,>(v: T): T => v;const withDefault = <T = string,>(v: T): T => v;const pair = <A, B>(a: A, b: B) => [a, b];Use a
.tsor.mtssource when an annotation needs the bare<T>form.An element's tag can carry type arguments, as in TypeScript's
.tsx. They are erased, in every extension above, so the element is the same call it is without them. A tag name followed by<always opens type arguments, because no type parameter list is written that way. As in TypeScript, a<on the line after an expression continues that expression, soafollowed by<b<c>don the next line is a comparison. The JSX transformer does not parse statements, so it reads every line break after a name, literal,),]or}that way, including afterif (ok),elseor a block: there a typed element that starts a statement is written in parentheses or after a;. A closing tag takes none.const choice = <Select<Option> items={options} />;const list = <List<number>>{items}</List>;
Arrow Return Types in Conditionals
Inside a conditional's consequent, (x) : y => z reads two ways: an arrow with return type y, or the parenthesized expression (x), the conditional's :, and an alternate arrow y => z. GocciaScript follows TypeScript's rule: there, the return-typed arrow is kept only when the : that closes the conditional follows its body. One : is needed for each consequent the arrow is nested in. Otherwise the group is a parenthesized expression, so plain JavaScript such as minified c ? (l) => ({ a: 1 }) : (l) => 2 parses as written.
const pick = c ? (x: number): number => x : (y: number) => -y; // return-typed arrowconst make = c ? (l) => ({ a: 1 }) : (l) => 2; // `({ a: 1 })` is the body
Automatic Semicolon Insertion and Type Syntax
Type-level declarations that are skipped rather than parsed (type, import type, export type) are erased whole under ASI, even when they span lines: a union | or intersection & leading the next line, a break right after the =, a break before a function type's =>, and a conditional type broken around ? and : all stay part of the declaration. A type argument list wrapped across lines is fine too, because its breaks fall after a < or , or before a >.
A type query keeps its operand across a line break the same way an operator does, so let value: typeof followed by source on the next line reads as one annotation.
This only applies when ASI is enabled; see Language for the opt-in flag and the general rules.
Both ! forms are restricted productions: the ! must appear on the same line as the binding name (definite assignment) or its operand (non-null assertion). A ! at the start of the next line begins a new expression statement, so ASI code such as let x followed by !fn() keeps its usual meaning. != and !== lex as single tokens and are never assertions.
Not Supported
- Namespaces (
namespace Foo { ... }). - Parameter properties in constructors (
constructor(public x: number)). - Angle-bracket type assertions (
<string>value) — usevalue as stringinstead. - Definite assignment assertions on class fields (
class C { x!: number }) — only variable declarations accept!.