0

Typescript is said to be an objected oriented form of javascript , allows type safety inheritance etc. But why it does not prevent to declare same name variable as its parameter inside body of method.

This could be very problematic specially when user forget and declare a variable with same name as its parameter and this cause overriding and lost of previous value stored in that variable.

Example Typescript:

function greeter(person : Person,b="") {

 var b = "3";

 //No warning in this case
} 

Example C#:

public  void greeter(Person person ,string b="")
    {

        string b = "3";

      //Error A local parameter name cannot be declare in sc
    }

Please help , or tell me is there any method to avoid such condition in Typescript?

Alessio
  • 3,404
  • 19
  • 35
  • 48
TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66

1 Answers1

1

Whilst this works with var, it won't be allowed if using let or const. E.g. this does not compile:

function greeter(person: Person, b = "") {
 const b = "3";
 // Error: Duplicate identifier 'b'
} 

In general, much of the JS community is moving away from var for many similar reasons, and using let & const instead will give you lots of extra safety.

If you'd like to enforce this, there are linting rules available for tslint and eslint.

Alternatively, it should be possible to write your own custom linting rule to disallow with var as well, but that will be substantially more work, and using let and const instead anyway has many other benefits.

Tim Perry
  • 11,766
  • 1
  • 57
  • 85