Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?
var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!
Current version of the compiler says:
Type 'String' is not assignable to type 'string'.
'string' is a primitive, but 'String' is a wrapper object.
Prefer using 'string' when possible.
Is that a bug?
Best Answer
Here is an example that shows the differences, which will help with the explanation.
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, sos2
in the example above creates a new string without the use of thenew
keyword and without explicitly using theString
object.string
is the TypeScript string type, which you can use to type variables, parameters and return values.Additional notes...
Currently (Feb 2013) Both
s1
ands2
are valid JavaScript.s3
is valid TypeScript.Use of
String
. You probably never need to use it, string literals are universally accepted as being the correct way to initialise a string. In JavaScript, it is also considered better to use object literals and array literals too:If you really had a penchant for the string, you could use it in TypeScript in one of two ways...