I have a string array named current_todos and am trying to add a variable of type (String | Nil) named new_task by doing the following:
current_todos << new_task if typeof(new_task) == String
I get the error Error: no overload matches 'Array(String)#<<' with type (String | Nil).
How can I add a nilable string to current_todos after doing a type check?
Edit: here is the full code:
require "option_parser"
current_todos = [
"Laundry",
"Walk dog",
"Sing in shower"
]
new_task = nil
OptionParser.parse do |parser|
parser.banner = "Welcome to my todo app!"
parser.on "-a TASK", "--add TASK", "Type a new task" do |task|
new_task = task
end
parser.on "-h", "--help" do
puts parser
exit
end
end
current_todos << new_task if typeof(new_task) == String
current_todos.each do |todo|
puts todo
end
If
new_taskis of typeString|Nil, you can test if it is non-nil. Then the compiler will know that it is a string. That here should work:Another way that the compiler will understand, which is closer to your original code, is to use
is_a?: