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 aDate
instance toparseInt
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
1 Answer
Reset to default 3Because 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
本文标签:
版权声明:本文标题:javascript - Why do I receive "Argument of type 'Date' is not assignable to parameter of type ' 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744289486a2599047.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论