1

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

3
  • but what is wrong in strings having methods? Commented Feb 17, 2024 at 17:23
  • 1
    The string type does indeed have all the methods of String in TypeScript. In JavaScript, a primitive string doesn't "have" methods, but it will become auto-wrapped in a String object if you treat it like it does. That means, pragmatically, strings in JavaScript also have methods. So String is the wrapper interface for string primitives, and string is essentially a subtype of String. (more) Commented Feb 17, 2024 at 17:26
  • 1
    (continued)The String interface is what gets updated when strings get new methods in TS, so it needs to exist. There is almost no "value-add" for String when it comes to users; just use string. Does that fully address the question? If so I'll write up an answer or find a dupe target; if not, what am I missing? Commented Feb 17, 2024 at 17:26

1 Answer 1

0

because it’s a type

When in doubt, check the source code of TypeScript, it’s all open source and free to view.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.