typescript 打字稿认为 getYear 在 Date 类型上不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40350288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript thinks getYear does not exist on type Date
提问by A. Duff
I'm running tsc inside a webpack project, with "core-js": "registry:dt/core-js#0.0.0+20160725163759"
and "node": "registry:dt/node#6.0.0+20160909174046"
我在 webpack 项目中运行 tsc,"core-js": "registry:dt/core-js#0.0.0+20160725163759"
并使用"node": "registry:dt/node#6.0.0+20160909174046"
Other date properties work fine:
其他日期属性工作正常:
private dateToString (date: Date) {
let month = date.getMonth();
let day = date.getDate();
let year = date.getYear() + 1900;
let dateString = `${month}/${day}/${year}`;
return dateString;
}
Typescript recognizes date.getMonth
and date.getDate
just fine, but on date.getYear
it gives
打字稿识别date.getMonth
并且date.getDate
很好,但在date.getYear
它上面给出
Property 'getYear' does not exist on type 'Date'.
Property 'getYear' does not exist on type 'Date'.
What definition am I missing?
我缺少什么定义?
回答by Drew Noakes
That API is deprecated. Try getFullYear()
instead.
该 API 已弃用。试试吧getFullYear()
。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
The getYear() method returns the year in the specified date according to local time. Because getYear() does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the getFullYear() method.
此功能已从 Web 标准中删除。虽然一些浏览器可能仍然支持它,但它正在被删除。不要在旧项目或新项目中使用它。使用它的页面或 Web 应用程序可能随时中断。
getYear() 方法根据当地时间返回指定日期的年份。由于 getYear() 不返回整年(“2000 年问题”),因此不再使用,并已被 getFullYear() 方法取代。
回答by Jerry Chong
Change this line from
将这一行从
let year = date.getYear() + 1900;
to
到
let year = date.getFullYear();