Last updated: Jan 22, 2023
Reading timeยท3 min
There isn't an official standard for whether you should use single or double quotes for TypeScript strings.
Most projects I've worked on have used single quotes unless having to escape a single quote character in the string, in which case double quotes are used.
// ๐๏ธ default const str1 = 'single quotes'; // ๐๏ธ when string contains single quote const str2 = "It's him"; const person = 'Bobby Hadz'; // ๐๏ธ backticks when interpolating variables const str3 = `hello ${person}`;
The example demonstrates when I would use single and double quotes in a TypeScript string.
If the string contains a single quote, it's much easier to wrap it in double
quotes than to escape the quote using a backslash character /
.
const str1 = "It's him"; const str2 = 'It\'s him'; const str3 = `It's him` // ๐๏ธ can also use backticks
The first string is much easier to read.
The third example uses backticks ``. But I mostly use backticks when I'm interpolating a variable in a string or when I have a multiline string.
It should be noted that some people link to the TypeScript contributor guidelines, which use double quotes for strings.
This is what they use in TypeScript's codebase, not what they recommend you use in your project.
So, it's easier for them to be consistent and not ask people to switch between single and double quotes depending on the programming language.
The main reason I prefer single quotes is - I don't have to use the shift
key
every time I declare a string.
Since most strings don't contain a single quote, I don't often have to use double quotes.
For multiline strings, I use backticks.
// ๐๏ธ (better) const longString = ` roses are red, violets are blue `; // ๐๏ธ (hard to read) const longString2 = 'roses are red\nviolets are blue';
The first example uses a template literal and is much easier to read than the second.
Some people prefer using double quotes for strings because JSON uses exclusively double quotes.
I don't find myself writing JSON manually as often as I find myself declaring strings, so that doesn't apply to me.
I also find it much easier to look at empty strings that were declared using single quotes.
const str1 = ''; const str2 = "";
Maybe I've gotten used to seeing single quoted strings over the years, but the second string from the example looks busy and unnecessary.
You can learn more about the related topics by checking out the following tutorials: