Home > Back-end >  Walrus operator TypeScript equivalent if statements
Walrus operator TypeScript equivalent if statements

Time:11-25

Extremely similar to this question, but w.r.t to if statements:

import { argv } from "process"

function foo(input: string): boolean
{
    return input === "ppp";
}

for (let i=0, v; v = foo(process.argv[2]) && i < 1; i  )
//if (let v = foo(process.argv[2]))
{
    console.log(v);
}
// console.log(v); <--- compile-time error, good !

Is there any way to define a Walrus-like operator inside if statements?

% npx tsc --target es2022 --moduleResolution node example.ts
example.ts:9:9 - error TS1005: ')' expected.

9 if (let v = foo(process.argv[2]))
          ~

CodePudding user response:

No, that's not possible with if. The IMHO best thing you can do if you want to narrow down the scope of your v is to create a new block

...
{ 
  let v= ...; 
  if (v) {
    ...
  }
  console.log(v); // no error here
} 
console.log(v) // compile error here
...

You can of course sort of abuse the for loop, by breaking out of it on the first iteration or setting v to a falsey. Similar to what you did with the i, but without the need of an additional variable.

for (let v = ...; !!v;) {
  console.log(v);
  break;
}

or

for (let v = ...; !!v; v=undefined) {  //or whatever falsey fits the type of your v
  console.log(v);
}

But IMHO both variants are quite ugly and not very intuitive. (The second seems slightly better) And if someone accidentially removes the break you end up in an endless loop.

I'd go with the additional block ...

And in your presented case, where v is actually a boolean, you don't need the variable at all. You can just do'

if (foo(...)) {
  console.log(true);
}

But I doubt you'll have booleans in all of your usecases ...

  • Related