23

Hi I am learning typescript.

I have in my code.

var name:string="Hello world";
console.log(name);

while compile time I am getting this error.

error TS2451: Cannot redeclare block-scoped variable 'name'.
index.ts(4,5): error TS2451: Cannot redeclare block-scoped variable 'name'.

Can someone describe me why I am getting this error?

2
  • 1
    In which context are you trying to execute this code ? Commented Nov 28, 2017 at 14:31
  • 2
    The error seems to suggest that you've already got a variable called name in scope. Commented Nov 28, 2017 at 14:37

3 Answers 3

21

The name property is defined on the window object:

interface Window extends EventTarget, WindowTimers, WindowSessionStorage, WindowLocalStorage, WindowConsole, GlobalEventHandlers, IDBEnvironment, WindowBase64, GlobalFetch {
    ...
    name: string;
    ...
}

(https://github.com/Microsoft/TypeScript/blob/master/lib/lib.d.ts#L17226)

You'll need to come up with a new name for your variable:

var myname = "Hello world";
console.log(myname);
Sign up to request clarification or add additional context in comments.

Comments

13

You can add export{} at the beginning of your file.

2 Comments

Could you explain a bit why to do so.
@rahul, the export {} makes it a module and so it has its own module scope and can thus use name without a class. See medium.com/@muravitskiy.mail/…
2

Your variable name has already been declared somewhere in the same block of code. And it is not allowed.

This is exactly the meaning of the error message.

The cause being that, you tried to declare this particular variable on global scope, and here name is already defined for some technical reason, for more details see : https://github.com/Microsoft/TypeScript/issues/9850

(Thanks @betadeveloper )

3 Comments

No. It is a global in the browser - window.name and in typescript they decided to declare it as a const, see this issue github.com/Microsoft/TypeScript/issues/9850
Thank you for the insight, I edited my answer adding the cause on this specific case.
@Pac0 Thanx Brother :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.