Skip to content
Static Types & Type Annotations
step 1/3

Reading — step 1 of 3

Adding Type Annotations to the Language

~2 min readType System & Optimization

Static Types & Type Annotations

Our language has been dynamically typed — type errors are caught at runtime. Now we add optional type annotations that enable static type checking: catching errors before the program runs.

Syntax

We extend the language with type annotations on variables, function parameters, and return types:

var x: number = 42;
var name: string = "hello";
var flag: bool = true;

fun add(a: number, b: number): number {
    return a + b;
}

The : type annotation is optional — if omitted, the type is inferred (we will add inference later). This is the approach used by TypeScript, Kotlin, and Python's type hints.

Type Grammar

type → "number" | "string" | "bool" | "nil" | "any"
     | "fun" "(" typeList? ")" ":" type
     | IDENTIFIER    // user-defined types (classes)

For now, our base types are:

  • number — double-precision float
  • string — text
  • bool — true or false
  • nil — the nil type (only value is nil)
  • any — escape hatch, compatible with everything

Parsing Annotations

The scanner already handles :. The parser needs to recognize type positions:

varDecl → "var" IDENTIFIER ( ":" type )? ( "=" expression )? ";"
funDecl → "fun" IDENTIFIER "(" paramList? ")" ( ":" type )? block
param   → IDENTIFIER ( ":" type )?

Storing Types in the AST

Each declaration node gains an optional typeAnnotation field. Each function node gains optional parameter types and a return type.

No Enforcement Yet

In this lesson, we only parse and store annotations. We do NOT enforce them yet. var x: number = "hello"; will parse successfully and the annotation is recorded, but no type error is reported. Type checking comes in the next lesson.

How TypeScript Does It

TypeScript adds type annotations to JavaScript and erases them during compilation — the emitted JavaScript has no types. This means TypeScript types have zero runtime cost. Our approach is similar: types are a compile-time concept that does not affect bytecode.

Your Task

Extend the scanner, parser, and AST to support type annotations on variables, function parameters, and function return types. Store them but do not enforce them yet.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…