Skip to content

TypeContracts.jlInterface contracts for Julia

Catch missing methods and wrong return types at precompilation time — before your code runs.

What is TypeContracts.jl?

TypeContracts.jl brings Go-style structural interface contracts to Julia. You declare which methods every concrete subtype of an abstract type must implement, annotate expected return types, and have violations caught at precompilation time — before your code ever runs.

julia
using TypeContracts

abstract type AbstractShape end
function area end
function perimeter end

@contract AbstractShape begin
    area(::Self)      :: Float64
    perimeter(::Self) :: Float64
end

struct Circle <: AbstractShape
    radius::Float64
end

area(c::Circle)::Float64      = π * c.radius^2
perimeter(c::Circle)::Float64 = * c.radius

@verify Circle   # passes at precompile time

struct Square <: AbstractShape
    side::Float64
end

area(s::Square) = s.side^2   # perimeter missing

@verify Square   # InterfaceError: module fails to load

Design philosophy

TypeContracts starts from structure: declare what methods must exist and what they must return, then enforce it. Behavioral testing (@invariants / test_behavior) is an addition on top of the structural foundation — the precompile-time guarantee is the anchor.

@contract / @verify    → methods exist, return types correct  (precompile time)
@invariants            → methods behave correctly             (test time)