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.
dd.toString().padStart(2, '0')
– Valdeir Psr