Bozo
Bozo

Reputation: 31

Need help understanding how these TypeScript declarations are different

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?

Upvotes: 1

Views: 65

Answers (2)

Top-Master
Top-Master

Reputation: 8751

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.

Upvotes: 3

saba silagadze
saba silagadze

Reputation: 46

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.

Upvotes: 0

Related Questions