I have read string primitive type in Typescript has no methods. It is just a value.
If we need methods (like toLowerCase() for example), we need to work with String type.
Here is what i’ve tried:
let s = "Hello";
console.log(typeof(s)); // string
s = s.toLowerCase();
I don’t understand: I have created a string variable and i was able to call toLowerCase method on it… Can you explain me why this is possible ?
And what’s the value-add of String ?
Thanks
>Solution :
In TypeScript and JavaScript, you can call methods on string primitives (like "Hello".toLowerCase()) due to a process called "autoboxing." This means when you invoke a method on a string primitive, the language temporarily converts it into a String object to access the method, and then it returns to being a string primitive after executing the method. This allows you to use methods without explicitly working with String objects.
The main difference between string primitives and String objects is that primitives are simple text values, while String objects are more complex and rarely needed in practice. Most of the time, you’ll work with string primitives because of their simplicity and efficiency, thanks to autoboxing which makes method usage transparent.