TypeScript - multiline string
In this article, we're going to have a look at how to create multiline string in TypeScript.
As multiline string we mean string that was divided into multiple lines only do me more readable by programmers.
Quick solution (use `
instead of '
or "
):
let text = `Line 1
Line 2
Line 3
Line 4
Line 5`;
console.log(text);
Note:
`
character (grave accent) is located togather with Tilde key - useShift
+~

There are few ways how to do it:
- template literals - introduced in ECMAScript 2015 (ES6),
+
operator with strings,- backslash at the end of each line - this approach is not part of standard.
1. Template literals (template strings) example
This approach was introduced in ES6 that is supported by TypeScript.
Main disadvantage of this approach are white space prefixes for each line if we want to format code clearly.
let text = `Line 1
Line 2
Line 3
Line 4
Line 5`;
console.log(text);
Output:
Line 1
Line 2
Line 3
Line 4
Line 5
2. +
operator with strings example
This approach solves problem of white character prefixes for formatted source code but introduces some complications about taking cate of "
and +
characters.
let text = 'Line 1' +
'Line 2' +
'Line 3' +
'Line 4' +
'Line 5';
console.log(text);
Output:
Line 1Line 2Line 3Line 4Line 5
3. Backslash at the end of each line example
This approach is very similar to template literals
and introduces problem with taking care of \
character at end of lines.
Note: this feature is not part of ECMAScript standard, so when source code is transpiled we should be sure it is transpiled to safe code too.
let text = 'Line 1\
Line 2\
Line 3\
Line 4\
Line 5';
console.log(text);
Output:
Line 1Line 2Line 3Line 4Line 5
4. Array
join
method example
This approach is more like cheat, but gives multiline string effect.
let array: Array<string> = [
'This',
'is',
'multiline',
'text.'
];
console.log(array.join('\n'));
Output:
This
is
multiline
text.