Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript asking for template literal

I'm using typescript, and is complaining when concatenating a string,

  const content = senderDisplay + ', '+ moment(timestamp).format('YY/MM/DD')+' at ' + moment(timestamp).format('h:mm A');

[tslint] Use a template literal instead of concatenating with a string literal. (prefer-template)

What is the template literal to fix this? cheers

like image 361
manuelBetancurt Avatar asked Mar 12 '18 02:03

manuelBetancurt


People also ask

What is a template literal?

Template literals are string literals allowing embedded expressions using backtick characters (`). You can use multi-line strings and string interpolation features with them.

What is literal in TypeScript?

A literal is a more concrete sub-type of a collective type. What this means is that "Hello World" is a string , but a string is not "Hello World" inside the type system.

Why would you need to use a template literal in JavaScript?

Template literals provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation.


1 Answers

You can see the template literals in MDN, and these are the prefered style in ES6.

In your case it would become the following:

const content = `${senderDisplay}, ${moment(timestamp).format('YY/MM/DD')} at ${moment(timestamp).format('h:mm A')}`;

Important differences:

  • Starts and ends with a backtick

  • Supports multiline strings

  • Expressions are interpolated with ${expression}

like image 135
Isac Avatar answered Oct 11 '22 04:10

Isac