Updating optional types in a function

Hi, I’m trying to figure out how to update optional types in a function. For example:

function example(foo:number?)
    if not foo then
        foo = 5
    end

    return 10 - foo
end

foo in the line return 10 - foo is underlined orange as number? cannot be converted to number, but I know that it will always be a number. How can I have the type checker recognize this? Or am I doing something wrong?

function example(foo: number)
	if (typeof(foo) ~= "number" or not foo) then
		foo = 5;
	end

	return 10 - foo;
end

Sorry I’m a little confused on what you’re trying to say, is this what you’re trying to achieve?

That’s really interesting. I would expect the type system to realize what’s going on but I guess not? I also tried explicitly checking against nil and got the same result.

The quick fix would be to just typecast foo as a number in the calculation since you 100% know that it will be a valid number and not nil.

function example(foo:number?)
    if not foo then
        foo = 5
    end

    return 10 - (foo :: number)
end
1 Like

This works, thank you!!!

1 Like