1

While reviewing some code, I came across a mix of capitalized types in a typescript document.

Is there an actual difference between these - because VSCode, colorizes them differently and gives reference for caps, and no ref for all lower (string vs. String etc)

errorMessage: String = '';  
errorShow: Boolean = false; 

errorMessage: string = '';  
errorShow: boolean = false; 

I've had no problems running the code either way - but am curious if there is a distinction / difference

j-p
  • 3,698
  • 9
  • 50
  • 93
  • 1
    See https://stackoverflow.com/a/34993650/10930232. You'll almost always want to use the primitive (lowercase) version. – 101arrowz Jan 28 '21 at 18:50

2 Answers2

1

String is the JavaScript String type, which you could use to create new strings. Nobody does this as in JavaScript the literals are considered better, so s2 in the example above creates a new string without the use of the new keyword and without explicitly using the String object.

string is the TypeScript string type, which you can use to type variables, parameters and return values.

zerocewl
  • 11,401
  • 6
  • 27
  • 53
0

For example:

var a = "hello world";
var b = 3.14159;
a.length; // 11
a.toUpperCase(); // "HELLO WORLD"
b.toFixed(4); // "3.1416"

The “how” behind being able to call a.toUpperCase() is more complicated than just that method existing on the value.

Briefly, there is a String (capital S) object wrapper form, typically called a “native,” that pairs with the primitive string type; it’s this object wrapper that defines the toUpperCase() method on its prototype.

When you use a primitive value like "hello world" as an object by referencing a property or method (e.g., a.toUpperCase() in the previous snippet), JS automatically “boxes” the value to its object wrapper counterpart (hidden under the covers).

A string value can be wrapped by a String object, a number can be wrapped by a Number object, and a boolean can be wrapped by a Boolean object. For the most part, you don’t need to worry about or directly use these object wrapper forms of the values—prefer the primitive value forms in practically all cases and JavaScript will take care of the rest for you.

From You Don't Know Js: Up & Going

Masoud Bimmar
  • 6,941
  • 4
  • 30
  • 33