Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript primitive string has no methods

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading