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?
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With