0

When I wrote below destructuring assignment code in TypeScript Playground.

const a = { name: 'teresa teng' };

let name;
({ name } = a);

console.log(name);

TSC throws:

'name' is deprecated.(6385)

lib.dom.d.ts(17642, 5): The declaration was marked as deprecated here.

Cannot assign to 'name' because it is a constant.(2588)

It works fine when I change the name to some "unique" name like userName. So I think some global variables are defined in TypeScript Playground, they are conflicts, right? If so, what are they?

TypeScript Playground

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • 1
    Ah, the joys of the browser global environment. You can't declare a global variable called `name`, it's a predefined property of the `window` object: https://developer.mozilla.org/en-US/docs/Web/API/Window/name If that code were in a module, or a function, or even just a scoping block, it would be fine: https://www.typescriptlang.org/play?module=1#code/N4KABBYMYPYHYGcAuYCGYC8ZhjqgtgKYBcYA5EoQE6ELqVwDmZYAvgNwjiQA2hKeIp0hgAFDkGE2mNAEpO3CLEQw+AOh4xGoyfJCsgA – T.J. Crowder Oct 14 '22 at 08:41
  • 1
    @T.J.Crowder Got it. Thanks. I thought it runs in some kind of sandbox or NodeJS module scope, not the browser global scope. – Lin Du Oct 14 '22 at 08:43
  • That's an interesting point. I don't see an option to control what the context of the code is in the playground. There's an option to control what the *output* module format is, but... I never noticed that before. :-) – T.J. Crowder Oct 14 '22 at 09:11
  • 1
    @T.J.Crowder Or using a top-level `export {}` to make this file as a module. "In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well)." – Lin Du Oct 14 '22 at 09:35
  • Of course! No *setting* for it, but anything with `import` or `export`... :-) – T.J. Crowder Oct 14 '22 at 09:49

0 Answers0