Concatenate a string with number in Typescript

Asked

Viewed 1,326 times

1

I’m trying to add a 0 in the formatting of my date/month, but I’m not able to concatenate 0 with a string.

I tried something like:

var dd = dataAtual.getDate();

if (dd < 10) {
  dd = '0' + dd
}

I get:

Type 'string' is not Assignable to type "number"

I also tried to:

if (mm < 10) {
   mm = 0 + mm;
}

But in this way appears only "6" instead of "06".

  • 1

    dd.toString().padStart(2, '0')

1 answer

2


Unlike Javascript which has weak typing, Typescript does not allow automatic coercion of types that may bring problems in some circumstances, so the only way to handle values of different types is by converting one of them to compatibilize, how you want it to be text should create a String or convert using the method toString().

There is another question. The fact that the language is static typing, for the good in my view, a variable cannot change type, so the variable that was number cannot receive a text, so you must create another variable with the type String to receive the results.

I will put in JS because the syntax is identical in both languages, the semantics is what changes, the beauty of TS is just this, not let a possible error occur, anything else:

function teste() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1;
    var yyyy = today.getFullYear();
    var d = "";
    var m = "";
    if (dd < 10)
        d = '0' + String(dd);
    if (mm < 10)
        m = '0' + String(mm);
    console.log(d);
    console.log(m);
}
teste();

Or if you prefer:

function teste() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1;
    var yyyy = today.getFullYear();
    var d = "";
    var m = "";
    if (dd < 10)
        d = '0' + dd.toString();
    if (mm < 10)
        m = '0' + mm.toString();
    console.log(d);
    console.log(m);
}
teste();

Note that you can turn the number into text of the two forms as I put them, they are interchangeable, you can choose which one to find best.

If you prefer you can do as Valdeir spoke and works well in both languages, it is an even more recommended way for generic solution because you will have problems with the months 10, 11 and 12:

function teste() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1;
    var yyyy = today.getFullYear();
    var d = dd.toString().padStart(2, '0');
    var m = mm.toString().padStart(2, '0');
    console.log(d);
    console.log(m);
}
teste();

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.