TypeScript:如何计算从日期到今天的天数

时间:2019-12-15 07:07:29

标签: typescript

const calculateDays = (joinedDate: string) => {
   const oneDay = 24 * 60 * 60 * 1000;
   const today = new Date();
   const joined = new Date(joinedDate);
   const diffDays = Math.round(Math.abs((today - joined) / oneDay));
 //                                        ^       ^
 //                                        error   error
   return diffDays;
 };
const days = calculateDays('2019-12-10T05:49:42.366Z')

我得到的错误是The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.ts(2362)

1 个答案:

答案 0 :(得分:1)

  

JavaScript调用valueOf方法将对象转换为原始值

Typescript仍然无法“理解”此模式。相关issue

作为解决方法,您可以强制编号:

const today = +new Date();
const joined = +new Date(joinedDate);