如何在Typescript中连接字符串和数字

Ann*_*a F 12 javascript concat typescript

我正在使用方法来获取数据

function date() {
    let str = '';

    const currentTime = new Date();
    const year = currentTime.getFullYear();
    const month = currentTime.getMonth();
    const day = currentTime.getDate();

    const hours = currentTime.getHours();
    let minutes = currentTime.getMinutes();
    let seconds = currentTime.getSeconds();
    if (month < 10) {
        //month = '0' + month;
    }
    if (minutes < 10) {
        //minutes = '0' + minutes;
    }
    if (seconds < 10) {
        //seconds = '0' + seconds;
    }
    str += year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds + ' ';

    console.log(str);
}
Run Code Online (Sandbox Code Playgroud)

作为输出,我得到了

2017-6-13 20:36:6 
Run Code Online (Sandbox Code Playgroud)

我想得到同样的东西,但是喜欢

2017-06-13 20:36:06 
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试其中一条线,我注释掉了,例如这一条线

month = '0' + month;
Run Code Online (Sandbox Code Playgroud)

我收到错误

Argument of type 'string' is not assignable to parameter of type 'number'.
Run Code Online (Sandbox Code Playgroud)

我怎么能连接字符串和数字?

Tyl*_*ler 34

模板文字(ES6 +)

而不是像month = '0' + month; 你可以使用模板文字串联

const paddedMonth: string = `0${month}`;
Run Code Online (Sandbox Code Playgroud)

然后你的字符串连接变成了这个例子:

str = `${year}-${paddedMonth}-${day} ${hours}:${minutes}:${seconds} `;
Run Code Online (Sandbox Code Playgroud)

更具可读性,IMO.

  • 如果正在使用TypeScript,它将在编译非es6时将模板文字转换为常规字符串连接. (4认同)

小智 7

如果您想使用日期,可以使用 momentjs 模块: https: //momentjs.com

moment().format('MMMM Do YYYY, h:mm:ss a'); // July 13th 2017, 11:18:05 pm
moment().format('dddd');                    // Thursday
moment().format("MMM Do YY");               // Jul 13th 17
moment().format('YYYY [escaped] YYYY');     // 2017 escaped 2017
moment().format();                          // 2017-07-13T23:18:05+04:30
Run Code Online (Sandbox Code Playgroud)

关于您遇到的错误,您最常使用的是这样的:

 let monthStr: string = month;
 if ( month < 10) {
     monthStr = '0' + month;
 }
Run Code Online (Sandbox Code Playgroud)