On Fri, Mar 22, 2024 at 10:31 AM Jordi Boggiano <j.boggi...@seld.be> wrote:
>
> On 2024-03-21 16:02, Robert Landers wrote:
>
> $a as int|float
>
> would be an int, float, or thrown exception.
>
> $a as int|float|null
>
> would be an int, float, or null.
>
> Just a suggestion here which might be more palatable to Rowan's wish for 
> consistency (which I can totally relate to):
>
> We perhaps could make sure that as does not throw if used with `??`, or that 
> `??` catches the type error and returns the right-hand expression instead:
>
> So to do a nullable typecast you would do:
>
>     $a as int|float ?? null
>
> To me this reads way more intuitive what will happen, and achieves the same 
> in an also very concise way.
>
> The only catch I see is that it would also swallow errors about $a not being 
> defined at all.
>
> Best,
> Jordi
>
> --
> Jordi Boggiano
> @seldaek - https://seld.be

Hey Rowan and Jordi,

I did a bit of research into other languages to see how they handle "as":

C#: as never throws, it either returns the type if it can be that type, or null
OCaml: fails if an alternative isn't given
Typescript: doesn't actually do anything, just hints the type for the compiler

After asking an AI for some examples and usages, the most compatible
one would be C#'s. In actuality, I think it could be hugely simplified
if we simply return null instead of throwing. There'd be no special
case for |null, and it would move the decision making to the
programmer:

$x = $a as int ?? throw new LogicException();

It also still allows for concisely making calls:

$x = ($a as MyType)?->doSomething();

What do you think?

Reply via email to