types_from_serializers
types_from_serializers copied to clipboard
Extract type from Rails enums
Description 📖
This adds support for enums in Rails. Defined enums will be converted to a union type with its allowed values.
Background 📜
Rails enums are currently converted to "any" types. In our own app we've been adding manual types with something like this:
class SongSerializer < BaseSerializer
attributes(
:id,
:title,
genre: { type: "'pop'|'rock'|'classical'" },
)
end
This PR aims to make it automatic.
The Fix 🔨
This extracts the possible values for the enum and adds them as a type:
class Song < ApplicationRecord
belongs_to :composer
has_many :video_clips
+ enum genre: { disco: "disco", rock: "rock", classical: "classical" }
+ enum tempo: %w[slow medium fast]
end
export default interface Song {
id: number
composer: Composer
+ genre: "disco" | "rock" | "classical"
+ tempo: "slow" | "medium" | "fast"
title?: string
}
I've added a test for the integer-enum as well as string-enum.
The added code in the generator is mildly atrocious - perhaps we can pass in the model here? Feedback welcome.
Any idea when this could be merged?
This would be an awesome addition to the library 👍
This is a nice addition, thanks @tijmenb!