Having trouble concatenating two strings in TypeScript

I am trying to concatenate two strings in TypeScript like this:

let string1 = new String("IdNumber: " + this.IdNumber);
let string2 = new String(this.notes);
this.notes = string1.concat(string2.toString());

The output I see for this.notes on line 3 is missing the original text from this.notes in string2.
This is what I see in devTools for this.notes on line 3 when debugging:

"IdNumber: 524242

" 

when hovering over this.notes on line 2 in devTools it looks like this:

"testing

 testing 2

 testing 3"

I was hoping that this.notes on line 3 would look like this:

"IdNumber: 524242

 testing

 testing 2

 testing 3"

What am I doing wrong?

>Solution :

I think a more ergonomic (if not idiomatic) approach would be using template literals, for example:

Code in TypeScript Playground

const example = {
  IdNumber: 524242,
  notes: 'testing\n\ntesting 2\n\ntesting 3',
  update () {
    this.notes = `IdNumber: ${this.IdNumber}\n\n${this.notes}`;
  },
};

console.log(example.notes); // "testing\n\ntesting 2\n\ntesting 3"
example.update();
console.log(example.notes); // "IdNumber: 524242\n\ntesting\n\ntesting 2\n\ntesting 3"

Leave a Reply