2

Consider this scenario, where I accidentally redefine the 'name' string:

function printName( name:string )
{
   let name = "Oops!";
   console.log(name);
}

In this case, I WANT a compile-time error. And, I get one. TypeScript gives "Duplicate identifier 'name'" at compile time. Life is good.

But now when I add try/catch, I no longer get an error.

function printName(name: string )
{
    try
    {
        let name = "Oops!";
        console.log("printName: " + name);
    }
    catch (e)
    {
        console.log("error:", e);
    }
}

Why don't I get an error anymore? Is there anything I can do to still get the same error at compile-time?

EDIT: Apparently if I put the code inside any kind of block (such as if-else), I don't get an error when I redefine a parameter. Apparently TypeScript in this case just figures I want to make a new variable, in its own scope, so the inner name becomes name_1. Is there any way I can get a warning or error for this?

Vern Jensen
  • 3,449
  • 6
  • 42
  • 59

2 Answers2

3

There is no way to get TypeScript itself to produce an error in that case.

An error is generated in your first example because that sample will actually produce an error at runtime, something like:

SyntaxError: Identifier 'name' has already been declared

However, in the second case, you shadow the name variable in your try block, which is not per se a problem. It should be fine at runtime (in that it won't throw an error).

But tools exist outside of the TypeScript compiler to help catch such issues. In particular, most linters have a no-shadow rule, such as ts-lint's no-shadowed-variable setting.

CRice
  • 29,968
  • 4
  • 57
  • 70
1

The reason that your let name = "Opps!" is inside of try/catch block and has own scope.

Read this What's the difference between using "let" and "var" to declare a variable in JavaScript?

vich
  • 262
  • 2
  • 15