1
$\begingroup$

Take this example program in modern Angular:

@if (user.profile.settings.startDate; as startDate) {
  {{ startDate }}
}

Why does there need to be a ; before as?

Modern Angular is based on TypeScript, and as usually doesn't require a ; before it. For example, this is an example TypeScript program:

if (process.env.NODE_ENV !== 'production') {
    (WithUser as any).displayName = wrapDisplayName(Component, 'withUser');
}

And here as is not preceded by a ;.

Now, admittedly, the semantics is different, as in the first example it's not about casting to another type (as it is in the second example), but it is about storing it to a variable.

How does Angular parse that? Does it have a keyword such as ;as different from as, or? The tokenizer for my programming language has a loop at the end of it that's merging series of tokens such as : and = into a single token:

 for (unsigned int i = 1; i < tokenizedExpression.size(); i++)
    if (tokenizedExpression[i].text == "=" and
        (tokenizedExpression[i - 1].text == ":" // The ":=" assignment operator.
         or
         tokenizedExpression[i - 1].text == "+" // The "+=" assignment operator.
         or tokenizedExpression[i - 1].text == "-" or
         tokenizedExpression[i - 1].text == "*" or
         tokenizedExpression[i - 1].text == "/" or
         tokenizedExpression[i - 1].text == "<" or
         tokenizedExpression[i - 1].text == ">")) {
      tokenizedExpression[i - 1].text = tokenizedExpression[i - 1].text + "=";
      tokenizedExpression.erase(tokenizedExpression.begin() + i);
    }

But this is, as far as I know, considered a bad praxis, isn't it? So, is Angular doing something similar?

$\endgroup$

1 Answer 1

3
$\begingroup$

In Angular's @if condition syntax, the as keyword is a binding of the conditional value and is not same as (the type assertion operator) from TypeScript.

This is analogous to:

if(let startDate = user.profile.settings.startDate) { ... }

(In programming languages where assignment is an expression. Like Python's walrus operator.)

Since the expression preceding Angular's as is itself TypeScript and hence can contain as-assertions, the semicolon is there to disambiguate TypeScript as from Angular as, because they're two different things.

From a language design perspective, it might have been a poor choice to re-use and overload as's meaning. The reasons are probably historical.

$\endgroup$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.