Is there an equivalent in Sorbet to Typescript's Pick?

Viewed 52

A colleague is trying to write a method that returns a subset of fields outlined in a T::Struct, and we're wondering if there is a Sorbet analog to Typescript's Pick, where only properties of an object that are explicitly mentioned in the type def are retained.

1 Answers

There isn't. In gerenal, Sorbet leans more heavily towards nominal typing, whereas TypeScript leans towards structural typing.

With Sorbet, you would use an interface to declare the crucial parts that define your abstraction. For example,

module Person
  extend T::Sig
  extend T::Helpers

  sig { returns(String) }
  def name; end

  sig { returns(Date) }
  def dateOfBirth; end
end

class Employee < T::Struct
  include Person

  const :name, String
  const :dateOfBirth, String
  const :department, String
  const :salary, Integer
end

As compared to Pick (and structural typing in general), using named types means that you can use their names to communicate purpose and meaning. Rather than a being a bucket of ints, dates and strings, an object that implements the Person interface has a very specific semantic meaning.

Related