Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explicitly passing nil does not set serialized value to nil #7702

Open
jez opened this issue Feb 14, 2024 · 0 comments
Open

Explicitly passing nil does not set serialized value to nil #7702

jez opened this issue Feb 14, 2024 · 0 comments
Labels
enhancement New feature or surprising current feature good first issue Good for newcomers runtime Related to the sorbet-runtime gem

Comments

@jez
Copy link
Collaborator

jez commented Feb 14, 2024

Input

→ View on sorbet.run

# typed: true
require 'sorbet-runtime'

class MyEnum < T::Enum
  enums do
    X = new(nil)
  end
end

T.reveal_type(MyEnum::X.serialize) # => NilClass
p(MyEnum::X.serialize)             # => "x"

Observed output

editor.rb:10: Revealed type: NilClass https://srb.help/7014
    10 |T.reveal_type(MyEnum::X.serialize) # => NilClass
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  Got NilClass originating from:
    editor.rb:10:
    10 |T.reveal_type(MyEnum::X.serialize) # => NilClass
                      ^^^^^^^^^^^^^^^^^^^
Errors: 1

When this runs, it shows "x".

Expected behavior

It should be possible to specify the default serialized value of an enum to nil. Sorbet believes this is possible statically, and says the type is NilClass.

But at runtime, the value printed is "x", because sorbet-runtime does not distinguish between "explicitly passed nil for the serialized value" vs "passed no arguments."


Ideally, we fix this in sorbet-runtime using something like a private constant:

private_constant :UNSET
def initialize(serialized_value = UNSET)

and we check whether serialized_value is UNSET instead of whether it's nil to determine whether to infer a string serialized value.

@jez jez added bug Something isn't working good first issue Good for newcomers runtime Related to the sorbet-runtime gem enhancement New feature or surprising current feature and removed bug Something isn't working labels Feb 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or surprising current feature good first issue Good for newcomers runtime Related to the sorbet-runtime gem
Projects
None yet
Development

No branches or pull requests

1 participant