Typescript: let name: string = "bob"; doesn't work.

Created on 15 Apr 2016  ·  3Comments  ·  Source: microsoft/TypeScript

Hello, I start to use TypeScript recently. It's super useful language for me :)
By the way, I'm in a tutorial about String Type in here https://www.typescriptlang.org/docs/handbook/basic-types.html

TypeScript Version:

1.8.10

Code

It _doesn't_ work.

_hello.ts_

let name: string = "bob";

Whenever I compile, the compiler will emit the following.

$ tsc hello.ts
../../usr/local/lib/node_modules/typescript/lib/lib.d.ts(16757,13): error TS2451: Cannot redeclare block-scoped variable 'name'.
hello.ts(1,5): error TS2451: Cannot redeclare block-scoped variable 'name'.

It works.

_hello.ts_

let aname: string = "bob";

Expecting Behavior

I read a part of the lib.d.ts and it has declare var name: string;. So I may understand the compiler emits an error. However what concept cannot we use the variable name in TypeScript?
And I think the tutorial which doesn't work is not good :(
Or is there something is wrong with me? I hope to replay an answer :)

Question

Most helpful comment

Because there is already a variable called name on the _global scope_. Try it out in your browser, console.log(name) and you will see an empty string (or maybe some other string) instead of undefined.

Fix

Put your name variable in a _module_ or namespace : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

All 3 comments

Because there is already a variable called name on the _global scope_. Try it out in your browser, console.log(name) and you will see an empty string (or maybe some other string) instead of undefined.

Fix

Put your name variable in a _module_ or namespace : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

Documentation for this variable : https://developer.mozilla.org/en-US/docs/Web/API/Window/name :rose:

@basarat
Thank you for your answer. That has such a meaning...
I didn't know there is already name variable in global scope :)

@DanielRosenwasser
Thank you for fixing the document, too :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jbondc picture jbondc  ·  3Comments

manekinekko picture manekinekko  ·  3Comments

remojansen picture remojansen  ·  3Comments

wmaurer picture wmaurer  ·  3Comments

weswigham picture weswigham  ·  3Comments