False positive "Unreachable code detected.ts(7027)"?

Viewed 435

Following snippet returns Unreachable code detected.ts(7027) on console.log(). Running on Visual Studio Code v1.43.2.

const foo = (() => {
  try {
    // operation like "return fs.readFileSync("./credentials.json")" is more likely to fail (nodejs)
    // following line is just placeholder
    return { val: 4 };
  } catch (err) {
    return { val: -1 };
  }
})();

console.log(foo.val); //vs throws unreachable

TypeScript Playground example

Is it really a false positive?

1 Answers

If you really wanted to implement it this way, you'd need to have some sort of fallback for val if the catch occurs.

Implement it this way:

const foo = (() => {
  let val = undefined
  try {
    val = 4
  } catch (err) {
    throw new Error(err);
  }
  return { val }
})();

console.log(foo.val);

It may be just an issue with TypeScript, but this will fix the problem. that TS is moaning about.

Related