admin管理员组

文章数量:1406010

I have a function that takes a date object as an argument. This function returns a different date.

function makeDate(date:Date) {
  return new Date(date); //<--error here
}
const newDate = new Date(); //
console.log(makeDate(newDate)); // Returns date object just fine

Typescript in Vscode shows the followinng error:

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

While the official docs state the Date constructor can take a number (milliseconds), a string (date string), there seems to be no issue with creating a date object by passing another date object into the Date constructor. Therefore, I would expect to receive no error.

I've Googled for this result, but the SO and Github issues I found don't seem to answer this or explain the issue (or at least I am not understanding the explanation as it relates to my example).

Should I be getting this error? And is there a way to fix it?

Thanks!

I have a function that takes a date object as an argument. This function returns a different date.

function makeDate(date:Date) {
  return new Date(date); //<--error here
}
const newDate = new Date(); //
console.log(makeDate(newDate)); // Returns date object just fine

Typescript in Vscode shows the followinng error:

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

While the official docs state the Date constructor can take a number (milliseconds), a string (date string), there seems to be no issue with creating a date object by passing another date object into the Date constructor. Therefore, I would expect to receive no error.

I've Googled for this result, but the SO and Github issues I found don't seem to answer this or explain the issue (or at least I am not understanding the explanation as it relates to my example).

Should I be getting this error? And is there a way to fix it?

Thanks!

Share Improve this question asked Feb 8, 2019 at 22:12 BrandonBrandon 1,8272 gold badges16 silver badges23 bronze badges 1
  • The Date constructor coerces the object argument to a primitive, and TypeScript doesn't like that. You can pass a Date instance to parseInt as well and it "works" - but it's the kind of code that TypeScript tries to avoid. – Bergi Commented Feb 8, 2019 at 22:27
Add a ment  | 

1 Answer 1

Reset to default 3

Because the constructor is expecting a string or a number, use getTime will fix it

function makeDate(date:Date) {
  return new Date(date.getTime()); //<--error here
}
const newDate = new Date(); //
console.log(makeDate(newDate)); // Returns date object just fine

本文标签: