'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?
Solution 1:[1]
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
Numbertype as well.
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | saba silagadze |
