Quick Reference
This guide is a quick reference for people already somewhat familiar with Sorbet. For getting started with Sorbet, see Adopting Sorbet.
Enabling type checking
To enable static checking with srb
, add this line (called a
sigil) to the top of your Ruby file:
# typed: true
This file will now be checked by Sorbet!
However, not much will really change. Sorbet knows about the types of methods in the standard library, but not methods we’ve defined ourselves. To teach Sorbet about the types of our methods, we have to add signatures above the method:
# typed: true
# (1) Bring T::Sig into scope:
require 'sorbet-runtime'
class Main
# (2) extend T::Sig to get access to `sig` for annotations:
extend T::Sig
# (3) Add a `sig` annotation above your method:
sig {params(x: String).returns(Integer)}
def self.main(x)
x.length
end
# alternatively, for a method with no parameters:
sig {returns(Integer)}
def no_params
42
end
end
Now srb
and sorbet-runtime
will check that our Main.main
method is
given only String
s and returns only Integer
s:
srb
will do this with static checks.sorbet-runtime
will do this by wrappingMain.main
with dynamic checks that run every time the method is called.
Type System
The complete type system reference can be found to the left. Here’s a quick table of contents:
- Integer, String, T::Boolean – Class Types
- T.nilable – Nilable Types
- T.any – Union Types
- T.let, T.cast, T.must, T.assert_type! – Type Assertions
- [Type1, Type2] – Tuple Types
- {key1: Type1, key2: Type2} – Shape Types
- T.untyped
- T.noreturn
- T.type_alias – Type Aliases
- T::Array, T::Hash, T::Set, T::Enumerable – Generics in the Standard Library
- T.proc – Proc Types
- T.class_of
- T.self_type
- T.all – Intersection Types
How do I…
Figure out what’s going on?
There are a number of common strategies that help when tracking down confusing behavior in Sorbet:
Run Sorbet on a small example?
The easiest way to try out Sorbet on small examples is to use
sorbet.run, which runs sorbet
(the static component) in
your browser.
Run Sorbet on a small file?
Consider this file:
# -- foo.rb --
# typed: true
require 'sorbet-runtime'
class Main
extend T::Sig
sig {void}
def self.main
puts 'Hello, world!'
end
end
Main.main
To check it statically:
❯ srb tc foo.rb
Note: If there’s a
sorbet/config
file in the current directory, this command will potentially run on more than just this single file. Runsrb tc
from a different folder to check a single file in isolation.
To test out how the runtime checks work:
❯ bundle exec ruby foo.rb
Note that
foo.rb
can only reference constants in the file and the standard library.
Run Sorbet on a whole project?
Each Sorbet project should have a sorbet/config
file at the root of the
project, which describes how to typecheck the project. If we are at the root of
our project, we can check the whole project with:
❯ srb
For more information, see Adopting Sorbet.