Skip to content

Add support for the Option Chaining (?.) operator #41

@MeGaGiGaGon

Description

@MeGaGiGaGon

Issue type:

  • ➕ Feature request

Short description:

The optional chaining operator allows for short-circuiting operations instead of crashing on undefined values. This is very useful with functions that can return undefined, for example targetBlock on entities.

In this code

if (player.targetBlock().mod() == "Pipez") {}

If the player isn't looking at a block, the script will crash with a ".mod is not a property of undefined" error. The code I often use to fix this is

if (player.targetBlock() != undefined && player.targetBlock().mod() == "Pipez") {}

TypeScript does not accept this since it gives a race condition where the block might have changed. The correct way is something like

var _temp = player.targetBlock();
if (_temp != undefined && _temp.mod() == "Pipez") {}

With the TypeScript ?. replacement generated code when targeting es2019 or earlier being

var _a;
if (((_a = player.targetBlock()) === null || _a === void 0 ? void 0 : _a.mod()) == "Pipez") {}

Comparing all of this to if ?. was available:

if (player.targetBlock()?.mod() == "Pipez") {}

It's clear that this would be a massive win for ease of use and readability. I am unsure what effect it would have on performance.

If this is impossible to add due to the backend, then the manual should be updated, as it says:

All features allowed by ECMAScript (ECMA-262) are available.

But does not specify which version of ECMAScript (ECMA-262) is available, with ?. having been added in version 10.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions