Type signatures with RBS, TypeProf and Steep
suggest changeRuby has no type annotations in its syntax, and it isn't going to get them. Since Ruby 3.0 the official answer to "how do I add types?" is RBS: a separate language for describing the types of Ruby classes, modules, methods and constants. Signatures live in .rbs files next to the code (or, since RBS 4.0, in comments inside the Ruby code), and tools read them:
- rbs: the gem that defines the language. It parses and validates signatures, ships signatures for the core classes and standard library, generates skeleton signatures and can check types at runtime while your tests run. It is bundled with Ruby since 3.0.
- TypeProf: a type inference tool that reads plain Ruby code and guesses signatures. Also bundled with Ruby.
- Steep: a static type checker. It reads your Ruby code and your RBS signatures and reports code that doesn't match them. Not bundled; install it as a development dependency.
This article walks through all three on small projects. Examples were run with Ruby 4.0, rbs 4.2, Steep 2.1 and the bundled TypeProf 0.31. Ruby 4.0 bundles rbs 3.10; Steep 2.1 pulls in rbs 4.2, which you need for the inline syntax described later.
Installing the tools
rbs and typeprof come with Ruby:
$ rbs --version
rbs 3.10.0
$ typeprof --version
typeprof 0.31.1
Steep goes into the Gemfile as a development dependency, which also gives you the newer rbs it depends on:
# Gemfile
group :development do
gem "steep", require: false
end
$ bundle install
$ bundle exec steep --version
2.1.0
$ bundle exec rbs --version
rbs 4.2.0
Run the tools with bundle exec so that rbs and Steep agree on the version.
Project layout
By convention signatures go in a sig/ directory that mirrors lib/:
shop/
Gemfile
Steepfile
lib/
inventory.rb
report.rb
sig/
inventory.rbs
report.rbs
For a gem, add sig/ to the files in the gemspec so users of your gem get the signatures too (see Gemspec Files). bundle gem already creates sig/<gem_name>.rbs and includes it.
Starting point: untyped Ruby
Here is the Ruby code we'll type:
# lib/inventory.rb
class Item
attr_reader :name, :price
def initialize(name, price)
@name = name
@price = price
end
def discounted(percent)
Item.new(name, price * (100 - percent) / 100)
end
end
class Inventory
def initialize
@items = {}
end
def add(item, count = 1)
@items[item.name] = [item, count]
self
end
def find(name)
entry = @items[name]
entry && entry.first
end
def total
@items.values.sum { |item, count| item.price * count }
end
def names
@items.keys.sort
end
end
inv = Inventory.new
inv.add(Item.new("pen", 150), 3).add(Item.new("book", 2000))
p inv.total
p inv.find("pen")&.discounted(10)&.price
2450
135
Writing signatures for an existing codebase by hand is tedious, so both rbs and TypeProf can write a first draft.
Generating a skeleton with rbs prototype rb
rbs prototype rb parses Ruby files and emits declarations for every class, method, attribute and instance variable it finds. It doesn't infer types, so almost everything is untyped:
$ rbs prototype rb lib/inventory.rb
class Item
@name: untyped
@price: untyped
attr_reader name: untyped
attr_reader price: untyped
def initialize: (untyped name, untyped price) -> void
def discounted: (untyped percent) -> untyped
end
class Inventory
@items: untyped
def initialize: () -> void
def add: (untyped item, ?::Integer count) -> self
def find: (untyped name) -> untyped
def total: () -> untyped
def names: () -> untyped
end
It picks up the obvious bits (count = 1 means an optional Integer, a method ending in self returns self), but the rest is up to you. Redirect the output into a file to start: rbs prototype rb lib/inventory.rb > sig/inventory.rbs.
There is also rbs prototype runtime, which loads the code and inspects the classes with reflection. As of rbs 4.2 it prints RBS::Prototype::Runtime is deprecated and is on its way out; prefer the rb variant or TypeProf.
Inferring types with TypeProf
TypeProf runs your code abstractly: it follows calls with types instead of values, starting from the code at the top level of the file, and records what each method receives and returns. Because our file ends with a few calls, it has something to work with:
$ typeprof --show-parameter-names --show-errors --no-show-typeprof-version lib/inventory.rb
# lib/inventory.rb
# (41,19)-(41,29):undefined method: [Item, Integer]#discounted
# (41,19)-(41,29):undefined method: Integer#discounted
class Item
def name: -> String
def price: -> Integer
def initialize: (String name, Integer price) -> void
def discounted: (Integer percent) -> Item
end
class Inventory
def initialize: -> void
def add: (Item item, ?Integer count) -> Inventory
def find: (String name) -> (Integer | Item | [Item, Integer])
def total: -> untyped
def names: -> Array[String]
end
That's much closer to real signatures, but it isn't perfect:
findis inferred asInteger | Item | [Item, Integer]. TypeProf tracks@itemsvalues as "array ofItemorInteger" rather than a 2-element tuple, soentry.firstcould be either, andentry && ...can return the array itself. The warnings at the top come from the same imprecision.totalisuntypedbecause TypeProf gave up onsumwith a destructuring block.
Treat TypeProf output as a draft to review. Use -o sig/inventory.rbs to write it to a file. TypeProf works best on code that is exercised by calls it can see, so pointing it at the whole project (typeprof lib test) gives better results than a single library file.
TypeProf also has an LSP mode (typeprof --lsp --stdio) that shows inferred signatures inline in the editor, without any .rbs files. The TypeProf VS Code extension uses it.
Writing the signatures
Here is the hand-tuned version of the signatures:
# sig/inventory.rbs
class Item
attr_reader name: String
attr_reader price: Integer
def initialize: (String name, Integer price) -> void
def discounted: (Integer percent) -> Item
end
class Inventory
@items: Hash[String, [Item, Integer]]
def initialize: () -> void
def add: (Item item, ?Integer count) -> self
def find: (String name) -> Item?
def total: () -> Integer
def names: () -> Array[String]
end
To make find match its signature exactly I also changed its body to entry&.first, which returns nil or the Item. rbs validate checks that a set of signatures is well-formed, for example that every type name exists:
$ rbs -I sig validate
No output means no problems. -I sig adds the directory to the signatures the command loads; core and stdlib signatures are always loaded.
RBS syntax tour
RBS looks like Ruby without method bodies. The most common pieces:
| Syntax | Meaning |
|---|---|
def name: (String a, ?Integer b) -> bool |
method; ? marks an optional argument |
def m: (*String rest, **Integer opts) -> void |
splat and double splat |
def m: (name: String, ?age: Integer) -> void |
required and optional keyword arguments |
def m: () { (Integer) -> void } -> void |
method that requires a block |
def m: () ?{ (Integer) -> void } -> void |
method with an optional block |
def self.create: () -> instance |
singleton (class) method; instance is an instance of the class |
def m: (Integer) -> Integer | (String) -> String |
overloads |
String? |
String or nil (shorthand for String | nil) |
Integer | Float |
union |
[String, Integer] |
tuple: an array with exactly these element types |
{ name: String, age: Integer } |
record: a hash with these symbol keys |
:red | :green, "GET", 42 |
literal types |
Array[String], Hash[Symbol, Integer] |
generic types |
bool, void, nil, untyped, self, top, bot |
special types |
@name: String |
instance variable |
attr_reader name: String |
attribute (also attr_writer, attr_accessor) |
NAME: String |
constant |
type id = Integer | String |
type alias |
A few rules that trip people up:
- Use
boolfor true/false results.boolishmeans "any value used as a condition", which is what block results usually are. voidmeans "the return value shouldn't be used". It's the right return type forinitializeand for methods called only for their side effects.untypedturns off checking for that value. It's the escape hatch for code you can't type yet.
Here is a larger example that uses generics, interfaces, aliases, overloads, mixins and blocks:
# sig/tour.rbs
module Shapes
type point = [Float, Float]
type color = :red | :green | :blue
interface _Area
def area: () -> Float
end
class Circle
include Comparable
attr_reader radius: Float
attr_accessor color: color?
def initialize: (Float radius, ?color: color?) -> void
def area: () -> Float
def <=>: (Circle other) -> Integer?
def self.unit: () -> Circle
end
def self.total_area: (Array[_Area] shapes) -> Float
end
class Stack[T]
include Enumerable[T]
@items: Array[T]
def initialize: () -> void
def push: (T item) -> self
def pop: () -> T?
def each: () { (T item) -> void } -> self
| () -> Enumerator[T, self]
def size: () -> Integer
def empty?: () -> bool
end
class Config
def fetch: (String key) -> String
| [D] (String key, D default) -> (String | D)
def to_h: () -> Hash[Symbol, untyped]
def each_pair: () { (Symbol key, untyped value) -> void } -> void
end
Things to notice:
- Interfaces (names starting with
_) describe duck types.Shapes.total_areaaccepts an array of anything with anareamethod returningFloat, not only circles. Interfaces exist only in RBS; there is no Ruby counterpart. - Type aliases (
type color = ...) are lowercase and scoped to the module they're declared in. - Generic classes declare type parameters in brackets:
class Stack[T].include Enumerable[T]says that all theEnumerablemethods (map,select,first, ...) work on elements of typeT. That's all you need to declare for them;Enumerableonly requireseach. - Overloads list several method types separated by
|.Stack#eachreturnsselfwhen called with a block and anEnumeratorwithout one, which is how core classes are typed too. - Generic methods declare their type parameters before the parameter list:
[D] (String key, D default) -> (String | D). Whatever type you pass as the default is part of the result type.
The Ruby code it describes:
# lib/tour.rb
module Shapes
class Circle
include Comparable
attr_reader :radius
attr_accessor :color
def initialize(radius, color: nil)
@radius = radius
@color = color
end
def area = Math::PI * radius**2
def <=>(other) = radius <=> other.radius
def self.unit = new(1.0)
end
def self.total_area(shapes) = shapes.sum(0.0, &:area)
end
class Stack
include Enumerable
def initialize
@items = []
end
def push(item)
@items.push(item)
self
end
def pop = @items.pop
def size = @items.size
def empty? = @items.empty?
def each(&block)
return enum_for(:each) unless block
@items.each(&block)
self
end
end
class Config
def initialize(data = {}) = @data = data
def fetch(key, *default)
@data.fetch(key, *default)
end
def to_h = @data.transform_keys(&:to_sym)
def each_pair = to_h.each_pair { |k, v| yield k, v }
end
require_relative "lib/tour"
c = Shapes::Circle.new(2.0, color: :red)
p c.area.round(2), c > Shapes::Circle.unit
p Shapes.total_area([c, Shapes::Circle.unit]).round(2)
s = Stack.new.push(1).push(2).push(3)
p s.pop, s.map { it * 10 }, s.each.next
cfg = Config.new("port" => "8080")
p cfg.fetch("port"), cfg.fetch("host", nil)
cfg.each_pair { |k, v| puts "#{k}=#{v}" }
12.57
true
15.71
3
[10, 20]
1
"8080"
nil
port=8080
The first version of my signatures declared <=> as returning Integer, and Steep rejected it: Float#<=> returns Integer? (it returns nil for incomparable values like NaN), so the method body can be nil. More on Steep below.
Exploring signatures with the rbs command
The rbs command can answer questions about any loaded type, including core classes. rbs method shows the type of one method:
$ rbs method String center
::String#center
defined_in: ::String
implementation: ::String
accessibility: public
types:
(::int width, ?::string pad_string) -> ::String at <rbs gem>/core/string.rbs:2146:14...2146:55
int and string (lowercase) are aliases from core: int is Integer | _ToInt (anything with to_int), string is String | _ToStr. That's how RBS describes Ruby's implicit conversions.
Your own signatures work the same way with -I sig:
$ rbs -I sig method Stack each
::Stack#each
defined_in: ::Stack
implementation: ::Stack
accessibility: public
types:
() { (T item) -> void } -> self at sig/tour.rbs:32:12...32:43
| () -> ::Enumerator[T, self] at sig/tour.rbs:33:12...33:37
$ rbs -I sig ancestors Stack
::Stack[T]
::Enumerable[T]
::Object
::Kernel
::BasicObject
Other useful subcommands are rbs methods ClassName (all methods), rbs constant, rbs parse file.rbs (syntax check only) and rbs list.
Type checking with Steep
Steep compares your Ruby code against the signatures. steep init writes a commented Steepfile; a minimal one looks like this:
# Steepfile
D = Steep::Diagnostic
target :lib do
signature "sig"
check "lib"
configure_code_diagnostics(D::Ruby.default)
end
A target groups source files with the signatures used to check them. D::Ruby.default is the default strictness; D::Ruby.lenient reports fewer problems (good for starting on an existing codebase or for tests), D::Ruby.strict reports more.
With the Inventory signatures from before, steep check passes:
$ bundle exec steep check
# Type checking files:
..
No type error detected. 🫖
Now add a class that uses Inventory carelessly:
# lib/report.rb
class Report
def initialize(inventory)
@inventory = inventory
end
def line_for(name)
item = @inventory.find(name)
"#{item.name}: #{item.price / 100.0}"
end
def summary
"Total: " + @inventory.total
end
def restock(name)
@inventory.add(name, "5")
end
end
# sig/report.rbs
class Report
@inventory: Inventory
def initialize: (Inventory inventory) -> void
def line_for: (String name) -> String
def summary: () -> String
def restock: (String name) -> Inventory
end
$ bundle exec steep check
# Type checking files:
..F.
lib/report.rb:8:12: [error] Type `(::Item | nil)` does not have method `name`
│ Diagnostic ID: Ruby::NoMethod
│
â”” "#{item.name}: #{item.price / 100.0}"
~~~~
lib/report.rb:8:26: [error] Type `(::Item | nil)` does not have method `price`
│ Diagnostic ID: Ruby::NoMethod
│
â”” "#{item.name}: #{item.price / 100.0}"
~~~~~
lib/report.rb:12:16: [error] Cannot pass a value of type `::Integer` as an argument of type `::string`
│ ::Integer <: ::string
│ ::Integer <: (::String | ::_ToStr)
│ ::Integer <: ::String
│ ::Numeric <: ::String
│ ::Object <: ::String
│ ::BasicObject <: ::String
│
│ Diagnostic ID: Ruby::ArgumentTypeMismatch
│
â”” "Total: " + @inventory.total
~~~~~~~~~~~~~~~~
lib/report.rb:16:19: [error] Cannot pass a value of type `::String` as an argument of type `::Item`
│ ::String <: ::Item
│ ::Object <: ::Item
│ ::BasicObject <: ::Item
│
│ Diagnostic ID: Ruby::ArgumentTypeMismatch
│
â”” @inventory.add(name, "5")
~~~~
lib/report.rb:16:25: [error] Cannot pass a value of type `::String` as an argument of type `::Integer`
│ ::String <: ::Integer
│ ::Object <: ::Integer
│ ::BasicObject <: ::Integer
│
│ Diagnostic ID: Ruby::ArgumentTypeMismatch
│
â”” @inventory.add(name, "5")
~~~
Detected 5 problems from 1 file
Every one of these is a real bug: find can return nil, String#+ doesn't convert integers, and add wants an Item and an Integer. The fixed version:
# lib/report.rb
class Report
def initialize(inventory)
@inventory = inventory
end
def line_for(name)
item = @inventory.find(name)
return "#{name}: not found" unless item
"#{item.name}: #{item.price / 100.0}"
end
def summary
"Total: #{@inventory.total}"
end
def restock(name, price)
@inventory.add(Item.new(name, price), 5)
end
end
with def restock: (String name, Integer price) -> Inventory in the signature, and Steep is happy again. Note the return ... unless item guard: Steep narrows the type of a local variable after if, unless, case/when, is_a? and nil? checks, so after the guard item is Item, not Item?. item&.name would work too, giving a String?.
Steep starts a few worker processes and loads all the core signatures, so the first steep check on a project takes a while (around half a minute on my Windows machine). steep server (Steep 2.0+) keeps a daemon running that later steep check runs connect to, and in an editor the language server keeps everything loaded anyway.
Annotations inside Ruby code
Sometimes Steep can't infer a type you know. Steep reads a few comment annotations in Ruby code:
# @type var names: Array[String]
names = []
ids = [] #: Array[Integer]
# @type var declares the type of a local variable. The trailing #: Type comment is a type assertion: it tells Steep the type of the expression on that line ([] on its own would be Array[untyped]). Steep checks that the assertion is compatible and reports an error if it can't be.
Checking tests and gems
Add a second target for tests, usually with lenient diagnostics:
target :test do
signature "sig", "sig/test"
check "test"
configure_code_diagnostics(D::Ruby.lenient)
end
Libraries from the standard library that aren't loaded by default are added with library "json", library "net-http" and so on. For third-party gems, see the section on the RBS collection below.
Inline signatures (RBS 4 and Steep 2)
Keeping .rbs files in sync with the code is the most common complaint about RBS. RBS 4.0 added an experimental inline syntax that puts the types in comments right in the Ruby file, and Steep 2.0 can check such files directly. Turn it on per path in the Steepfile:
target :lib do
signature "sig"
check "lib", inline: true
end
# lib/temperature.rb
class Temperature
include Comparable
attr_reader :degrees #: Float
attr_reader :unit #: Symbol
# @rbs (Float degrees, ?unit: Symbol) -> void
def initialize(degrees, unit: :c)
@degrees = degrees
@unit = unit
end
#: () -> Temperature
def to_f
return self if unit == :f
Temperature.new(degrees * 9 / 5 + 32, unit: :f)
end
# @rbs other: Temperature
# @rbs return: Integer?
def <=>(other)
to_f.degrees <=> other.to_f.degrees
end
def to_s = "#{degrees.round(1)}°#{unit.upcase}" #: String
end
class Thermometer
# @rbs @readings: Array[Temperature]
#: () -> void
def initialize
@readings = []
end
# @rbs (Temperature reading) -> self
def record(reading)
@readings << reading
self
end
#: () -> Temperature?
def max = @readings.max
#: () -> String
def report
"max: " + max.to_s
end
end
No .rbs file is needed for these classes (sig/ can stay empty): steep check reads the types straight from the comments, and editors using the Steep language server show them on hover.
$ bundle exec steep check
# Type checking files:
.
No type error detected. 🫖
The inline types are checked just like types declared in .rbs files. Change report to use max.degrees instead of max.to_s and Steep points out that max returns Temperature?, which may be nil:
$ bundle exec steep check
# Type checking files:
F
lib/temperature.rb:48:18: [error] Type `(::Temperature | nil)` does not have method `degrees`
│ Diagnostic ID: Ruby::NoMethod
│
â”” "max: " + max.degrees.to_s
~~~~~~~
Detected 1 problem from 1 file
Likewise Temperature.new(20) is an error (Cannot pass a value of type ::Integer as an argument of type ::Float), because initialize was declared to take a Float.
The syntax has several equivalent forms:
# @rbs METHOD-TYPEor#: METHOD-TYPEon the line before adefgives the whole method type.# @rbs name: Typeand# @rbs return: Typegive one parameter or the return type at a time, with an optional description after--.- A trailing
#: Typeafterdef ... = expr, afterdef m(...)or afterattr_reader :xdeclares the return or attribute type. # @rbs @ivar: Typedeclares an instance variable.
Unannotated methods are (?) -> untyped: they accept anything and return untyped, so you can annotate a codebase gradually. As of RBS 4.2 the inline syntax doesn't support generic classes, class << self, visibility (private) or top-level methods; keep those in .rbs files. Both kinds of signatures can be used in one project.
The rbs-inline gem
Before inline syntax moved into RBS itself it was developed as a separate gem, rbs-inline. It uses a similar comment syntax (with a # rbs_inline: enabled magic comment at the top of each file) but works differently: the rbs-inline command generates .rbs files (by default into sig/generated/), which Steep and other tools then read like any hand-written signature. You'll see it in projects that started typing before RBS 4; for new code, the built-in inline support is the direction RBS is going.
Checking types at runtime with rbs test
Static checking only proves that the code agrees with the signatures. If the signatures themselves are wrong (and with untyped around, that's easy), nothing complains. rbs test closes the gap: it wraps the methods of the classes you choose and checks every call's arguments and return value against the signatures while your test suite runs.
# bad.rb
require_relative "lib/tour"
c = Shapes::Circle.new(2)
p c.area.round(2)
$ bundle exec rbs -I sig test --target 'Shapes::*' --target Config ruby bad.rb
...: TypeError: [Shapes::Circle#initialize] ArgumentTypeError: expected `::Float` (radius) but given `2` (RBS::Test::Tester::TypeError)
from bad.rb:2:in '<main>'
Circle.new(2) works fine in Ruby, but the signature says the radius is a Float. Here the decision is yours: either callers must pass floats, or the signature should accept Numeric.
Overloads are checked too. With Config.new("port" => 8080).fetch("port"), the return value 8080 matches neither overload of fetch:
WARN -- rbs: [Config#fetch] UnresolvedOverloadingError method_type=`(::String key) -> ::String` details=["ReturnTypeError: expected `::String` but returns `8080`"], ...
...: TypeError: [Config#fetch] UnresolvedOverloadingError: couldn't find a suitable overloading (RBS::Test::Tester::TypeError)
In practice you run the whole suite this way: bundle exec rbs -I sig test --target 'MyGem::*' bundle exec rake test. The same can be done with environment variables, which is handier in CI: RBS_TEST_TARGET='MyGem::*' RBS_TEST_OPT='-I sig' RUBYOPT='-rrbs/test/setup' bundle exec rake test. Runtime checking slows the code down noticeably, so keep it to a separate CI job (see Testing in CI).
Signatures for gems: the RBS collection
Your code calls gems, and Steep needs their signatures too. Gems can ship their own sig/ directory, and signatures for many popular gems that don't ship their own are maintained by the community in gem_rbs_collection. rbs collection downloads the right ones based on your Gemfile.lock:
$ bundle exec rbs collection init
$ bundle exec rbs collection install
rbs_collection.yaml lists the sources and any gems to skip or add:
sources:
- type: git
name: ruby/gem_rbs_collection
remote: https://github.com/ruby/gem_rbs_collection.git
revision: main
repo_dir: gems
path: .gem_rbs_collection
gems:
# Skip a gem whose signatures you don't want
# - name: nokogiri
# ignore: true
install writes rbs_collection.lock.yaml (commit it) and downloads signatures into .gem_rbs_collection/ (add it to .gitignore). Steep, rbs and TypeProf pick up rbs_collection.yaml automatically. Run rbs collection update after updating gems.
Editor support
- Steep is also a language server (
steep langserver). The Steep VS Code extension shows type errors as you type, hover types, completion and go-to-definition, including for inline annotations. - TypeProf in LSP mode shows inferred signatures above each method without requiring any
.rbsfiles. - Ruby LSP reads RBS signatures of core and standard library classes for hover and completion, highlights
.rbsfiles, and works next to the Steep extension, which provides the actual type checking.
Where to start
A realistic plan for adding types to an existing project:
- Add Steep to the Gemfile, run
steep init, and start with one directory andD::Ruby.lenient. - Generate drafts with
typeproforrbs prototype rb, then fix the types by hand. Leaveuntypedwhere it's hard. - Set up
rbs collectionfor your dependencies. - Run
steep checkin CI, and tighten diagnostics as coverage grows. - Run the test suite under
rbs testfrom time to time to catch signatures that lie. - For gems, ship
sig/in the gem so users get your types for free.
Summary
| Task | Command |
|---|---|
| Check signatures are well-formed | rbs -I sig validate |
| Skeleton from Ruby source | rbs prototype rb lib/foo.rb |
| Infer types | typeprof lib |
| Show a method's type | rbs method String center |
| Create a Steepfile | steep init |
| Type check | steep check |
| Inline types in Ruby files | check "lib", inline: true in Steepfile |
| Runtime checks in tests | rbs -I sig test --target 'MyGem::*' rake test |
| Signatures for gems | rbs collection init and rbs collection install |