typescript 类型错误:formats.dateTimeString.toISOString 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32156823/
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
TypeError: formats.dateTimeString.toISOString is not a function
提问by JB123
I'm new to TypeScript and AngularJS, and I'm trying to convert a date from my API that is something like:
我是 TypeScript 和 AngularJS 的新手,我正在尝试从我的 API 中转换一个类似于以下内容的日期:
"8/22/2015"
...to an ISO Date. The date is properly deserialized into a TypeScript property of type Date
. However, when I try the following command (in typescript, and this.dateDisplay
is of type string)
...到 ISO 日期。日期被正确反序列化为 type 的 TypeScript 属性Date
。但是,当我尝试以下命令时(在打字稿中,并且this.dateDisplay
是字符串类型)
this.dateDisplay = formats.dateTimeValue.toISOString();
I get the error:
我收到错误:
TypeError: formats.dateTimeValue.toISOString is not a function at dataFormatsTests.js:42 at processQueue (angular.js:14567) at angular.js:14583 at Scope.$get.Scope.$eval (angular.js:15846) at Scope.$get.Scope.$digest (angular.js:15657) at Scope.$get.Scope.$apply (angular.js:15951) at done (angular.js:10364) at completeRequest (angular.js:10536) at XMLHttpRequest.requestLoaded (angular.js:10477)
类型错误:formats.dateTimeValue.toISOString 不是 dataFormatsTests.js:42 at processQueue (angular.js:14567) at angular.js:14583 at Scope.$get.Scope.$eval (angular.js:15846) at Scope.$get.Scope.$digest (angular.js:15657) at Scope.$get.Scope.$apply (angular.js:15951) at done (angular.js:10364) at completeRequest (angular.js:10536) ) 在 XMLHttpRequest.requestLoaded (angular.js:10477)
I've also been to this siteand it says my browser supports the toISOString
function.
我也去过这个网站,它说我的浏览器支持该toISOString
功能。
So, my questions is: Why doesn't my browser, or angular, or whatever, recognize the toISOString
function?
所以,我的问题是:为什么我的浏览器或 angular 或其他任何东西都无法识别该toISOString
功能?
回答by JB123
Although the dateTimeValue was defined as a Date in TypeScript, it was being instantiated at runtime as a string because it was being pulled from the API. Therefore, the TypeScript would compile just fine, but when the javascript ran it was seeing .toISOString()
being called against a string, not a Date.
尽管 dateTimeValue 在 TypeScript 中被定义为日期,但它在运行时被实例化为字符串,因为它是从 API 中提取的。因此,TypeScript 可以很好地编译,但是当 javascript 运行时,它看到的.toISOString()
是针对字符串而不是日期调用的。
回答by Alamgir
Moment.js creates a wrapper for the Date object.formats.dateTimeValue is not wrapper object. To get this wrapper object, simply call moment() with one of the supported input types. so convert it like this:
Moment.js 为 Date 对象创建一个包装器。formats.dateTimeValue 不是包装器对象。要获取此包装器对象,只需使用受支持的输入类型之一调用 moment() 即可。所以像这样转换它:
this.dateDisplay = moment(formats.dateTimeValue).toISOString();
I have solved my problem like above.
我已经像上面一样解决了我的问题。