Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript ` vs ' vs "

Tags:

typescript

What is the difference in the following three string assignments?

let a: string = `my text`;
let b: string = 'my text';
let c: string = "my text";

They all work perfectly fine. It it just a matter of personal taste which one to use or are there differences?

like image 801
Socrates Avatar asked Apr 10 '26 04:04

Socrates


2 Answers

This is not actually related to Typescript. Its part of Javascript.

let a: string = `my text`; ---> template literal
let b: string = 'my text'; ---> just a string
let c: string = "my text"; ---> just a string

Template literals were added in ES6 and they allow interpolation:

let name = 'Martin';
let greetings = `Hello ${name}, how are you?`; // result: Hello Martin, how are you?
like image 196
Martin Nuc Avatar answered Apr 11 '26 17:04

Martin Nuc


Back ticks are actually part of JavaScript (template literals) and they allow embedding expressions. Typescript allows you to use them even if you're using an older version of JavaScript by transpiling it to string concatenation if you're targeting older JavaScript.

let user = "Socrates";
`Hi there ${user}` ; // Hi there Socrates
`Did you know your name is ${user.length} chars long?`;

As for the differences between double and single quotes, there is no difference, they allow you to avoid escaping the quote chars if only one type is used inside the string.

'I asked "how are you?"'; // clearer than "I asked \"how are you?\""
"Frankly my dear, I don't give a damn"; // vs don\'t
like image 35
Motti Avatar answered Apr 11 '26 18:04

Motti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!