← Back tothis vs that

string vs String

Written byPhuoc Nguyen
Category
TypeScript
Created
25 Aug, 2020
Last updated
20 Apr, 2022
Contributors
aycanogut
`string` and `String` are valid TypeScript types. The following declarations are valid:
let foo: String = 'foo';
let bar: string = 'bar';

Difference

`string` refers to the JavaScript's primitive types and can be created by using either literals (single or double quotes) or `String` function (without the `new` keyword).
The three declarations below create the same string:
const message = 'hello';
const message = 'hello';
const message = String('hello');
We often use `typeof variable === 'string'` to check if a given variable is a primitive string.
`String` on the other hand is an object that wraps the primitive string, and used to manipulate strings. We can create an instance of `String` from the constructor such as `new String(...)`:
const message = new String('hello');
In order to check whether a variable is an instance of `String` object, we have to use the `instanceof` operator:
if (variable instanceof String) {
...
}

Good to know

Given the declarations at the top of this page, you can assign a `String` object to a primitive `string` variable:
let foo: String = 'foo';
let bar: string = 'bar';

foo = bar; // OK
As the time of writing, `String` is declared as an interface so that the `string` is treated as a subtype of `String`. Assigning `foo = bar` therefore does not cause any problem.
But doing the opposite assignment will throw an error:
// ERROR: Type 'String' is not assignable to type 'string'.
// 'string' is a primitive, but 'String' is a wrapper object.
bar = foo;

Good practice

According to the official TypeScript's Do's and Don'ts, it is recommended to not use `Number`, `String`, `Boolean`, `Symbol`, or `Object`.
// Do NOT
const reverse = (s: String): String => {
...
}

// Do
const reverse = (s: string): string => {
...
}

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn