Optional Chaining doesn't work for Out-of-range array indexes
What
Using the Playground with the newest version 1.16 I expected Posts[10]?.Title to result in undefined whereas it throws
reflect: slice index out of range (3:6)
| Posts[10]?.Title
| .....^
Just like in JS [][1]?.a also works and yields null/undefined making things like [][1]?.a ?? 42 work where as Posts[10]?.Title ?? "default" does not work currently in with this library.
Or is this expected/deliberate?
In JS Posts[10] return undefined. This is why it is working in JS. In Expr Posts[10] will raise an error.
Not sure what is the best solution here.
Expr for this purpose have a special builtin function get(array, index).
It will return nil instead of raised error:
get(Posts, 10)?.Title
let post = Posts | get(10);
post?.Title
Another solution I'm looking into is adding an option to Expr to make all . access optional changing and to return nil insted of error on out of bound check.
Expr for this purpose have a special builtin function get(array, index)
But this would get bulky very fast wouldn't it?
I mean get(get(myDeepObject?.Prop, 10)?.NestedList, 1)?.value
Another solution I'm looking into is adding an option to Expr to make all . access optional changing and to return nil insted of error on out of bound check.
I would love that!
I already thought of writing a Patcher that makes all MemberNodes Optional by default. This as an global option would be greatly appreciated and I also do see value here for other people as it makes the syntax a whole lot easier to write for non technical users and everyone can decide if they want to turn this option on or off
I would love that! I already thought of writing a Patcher that makes all MemberNodes Optional by default. This as an global option would be greatly appreciated and I also do see value here for other people as it makes the syntax a whole lot easier to write for non technical users and everyone can decide if they want to turn this option on or off
I agree. Let's make an option to set all MemberNodes as optional.
Posts[10]
Make array access should return nil instead of rasing error by default. And have an option like expr.PanicOnOutOfBound().
Love it