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

标签 javascript typescript concat

我正在使用方法获取数据

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);
}

作为输出我得到了

2017-6-13 20:36:6 

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

2017-06-13 20:36:06 

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

month = '0' + month;

我收到错误

Argument of type 'string' is not assignable to parameter of type 'number'.

如何连接字符串和数字?

最佳答案

联合类型

您可以使用 union type声明变量时。

let month: string | number = currentTime.getMonth();

if (month < 10) {
  month = '0' + month;
}

模板文字 (ES6+)

或者,您可以创建一个新变量并使用 template literal

const paddedMonth: string = `0${month}`;

例如,您的字符串连接会变成这样:

str = `${year}-${paddedMonth}-${day} ${hours}:${minutes}:${seconds} `;

更具可读性,IMO。

关于javascript - 如何在 Typescript 中连接字符串和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088700/

相关文章:

mysql - 将字符串连接到 SELECT * MySql

sql - 如何使用 SQL CONCAT/SUBSTR?

javascript - 下载速度下降时在 Windows 中终止进程

javascript - 无法使用 typescript 创建 react 应用程序

angular - 如何在不需要 rxjs-compat 的情况下只导入 RxJS 6 中使用的运算符,如旧的 RxJS?

typescript - 实体与关系的持久化问题

mysql - 使用 sql 查询将文本添加到字段

javascript - Owl Carousel 在 IE11 win7 中不起作用(Js 冲突?)

javascript - 来自javascript的麦克风音量控制

javascript - 在 datalist 控件中调用 jquery 函数