String
and Object
types point to values stored in the "heap", similar to Java.
However, in TypeScript, string literals are typed as string
. The type String
refers to objects, while string
refers to "primitive values". For more information, MDN has a detailed article published here.
The definition of Object
is as follows (you may not understand its signature, but don't worry about it - it's not relevant):
interface Object {
constructor: Function;
toString(): string;
toLocaleString(): string;
valueOf(): Object;
hasOwnProperty(v: PropertyKey): boolean;
isPrototypeOf(v: Object): boolean;
propertyIsEnumerable(v: PropertyKey): boolean;
}
(Assuming you are familiar with Java's interface
, I will skip explaining what an interface
is)
In contrast, the type string
has the following members:
- An index signature of number which is similar to the
charAt(int)
method in Java,
Symbol.iterator
, mostly identical to CharSequence
's codePoint
method in Java,
- and various methods named after strings
TypeScript uses "structural typing", which differs from Java's "nominal typing" system. A key distinction between these systems is that structural typing assesses sub-typing based on the type's properties. In other words, in TypeScript, Hello
and Hi
are considered the same type, unlike in Java:
interface Hello {}
interface Hi {}
const hello: Hello = {};
// no compile errors
const hi: Hi = hello;
TypeScript evaluates the intersection set of properties to determine if a value can be assigned or passed. However, Object
and string
have no common properties at all! TypeScript raises an error to indicate this mismatch.
To resolve this, you can change String
to string
as suggested by other users.