1

Trying to understand the differences between these declarations:

let foo = new String('bar'); // StringConstructor
let foo = new Number(100); // NumberConstructor

let foo: String = 'bar'; // interface
let foo: Number = 100; // interface

var foo: string = 'bar'; // globally scoped?
var foo: number = 100; // globally scoped?

Are there any particular pros and cons to using different declarations over others?

kevinSpaceyIsKeyserSöze
  • 3,693
  • 2
  • 16
  • 25
Bozo
  • 31
  • 1
  • 4
  • 2
    I'm not sure how all of those groups relate to each other. In the first two cases, you are talking about types, but in the last case you bring up scope...and mix in typescript. What do you mean by all that? – smac89 Feb 05 '22 at 08:15
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String – ksav Feb 05 '22 at 09:32
  • https://stackoverflow.com/questions/14727044/what-is-the-difference-between-types-string-and-string – ksav Feb 05 '22 at 09:40
  • 1
    https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var – ksav Feb 05 '22 at 09:40

2 Answers2

3

JavaScript's primitive String is immutable, which is a huge difference between passing an object (created with new), vs passing the primitive (myVar = 'my-value';).

For example, try something like:

var myObject = new String('my value');
var myPrimitive = 'my value';

function myFunc(x) {
  x.mutation = 'my other value';
}

myFunc(myObject);
myFunc(myPrimitive);

console.log('myObject.mutation:', myObject.mutation);
console.log('myPrimitive.mutation:', myPrimitive.mutation);

Which should output:

myObject.mutation: my other value
myPrimitive.mutation: undefined

Note that the same applies to TypeScript, and to Number type as well.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
0

let/var are not related to Typescript, they are related to Javascript:

What's the difference between using "let" and "var"?

String created by calling "new String()" is typeof object and you should avoid it.

In second and third cases, "String" is Javascript object used for creating strings, "string" is typescript type which should be used for typing string variable.

  • As a TypeScript beginner I must say this isn't really helpful. What is a "typeof object"? And the last sentence doesn't really give any information IMO. – RoToRa Feb 05 '22 at 08:15
  • typeof is Javascript operator used for getting type of data. – saba silagadze Feb 05 '22 at 08:26
  • "string" is typescript type which Should be used, "String" is Javascript constructor used for creating strings which Shouldn't be used for typing. – saba silagadze Feb 05 '22 at 08:28