string vs String
Written byPhuoc Nguyen
Created
25 Aug, 2020
Last updated
20 Apr, 2022
Category
TypeScript
`string`
and `String`
are valid TypeScript types. The following declarations are valid:js
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:
js
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(...)`
:js
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:js
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:js
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:
js
// 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`
.js
// Do NOT
const reverse = (s: String): String => {
...
}
// Do
const reverse = (s: string): string => {
...
}
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
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