typescript 日期变量有效,但其上的函数无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30118383/
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
Date variable works, but functions on it do not
提问by Roy Dictus
I'm using TypeScript 1.4 in an ASP.NET MVC 5 project.
我在 ASP.NET MVC 5 项目中使用 TypeScript 1.4。
I have a field of type Date, and it works partially:
我有一个日期类型的字段,它部分工作:
var dob: Date = result.dateOfBirth;
alert(dob);
var dobAsString = dob.toDateString();
In the code above, the first two lines work, showing the value as "1968-11-16T00:00:00", as expected. But the last line doesn't work, in fact the rest of the code below that line isn't even executed -- it just breaks, without error message.
在上面的代码中,前两行工作,如预期的那样将值显示为“1968-11-16T00:00:00”。但是最后一行不起作用,实际上该行下面的其余代码甚至没有执行——它只是中断,没有错误消息。
This behavior persists no matter which Date function I apply in the last line; I could also use dob.getFullYear()
etc. and it would fail every time. Yet the variable is of the right type and has the right value. The compiler also finds the Date functions, it compiles without a hitch but at runtime it fails. Any ideas?
无论我在最后一行应用哪个 Date 函数,这种行为都会持续存在;我也可以使用dob.getFullYear()
等,但每次都会失败。然而变量是正确的类型并且具有正确的值。编译器还找到了 Date 函数,它可以顺利编译,但在运行时却失败了。有任何想法吗?
回答by Fenton
There are two aspects to this one. The first is that you need to parse the date, as you have a string representation currently. The second is that your result
variable doesn't have type information.
这有两个方面。第一个是您需要解析日期,因为您目前有一个字符串表示。第二个是你的result
变量没有类型信息。
var result = {
dateOfBirth: '1968-11-16T00:00:00'
};
// Error, cannot convert string to date
var a: Date = result.dateOfBirth;
// Okay
var b: Date = new Date(result.dateOfBirth);
var result2: any = result;
// Okay (not type information for result2)
var c: Date = result2.dateOfBirth;
When you get back a JSON message, you can apply an interface to it that describes what the server has send, in order to catch problems in your TypeScript code - such as the one you found. This will stop the problem occurring again in the future (although doesn't check the supplied JSON matches the interface)... the example below assumes result
currently has the any
type.
当您返回 JSON 消息时,您可以对其应用一个接口来描述服务器已发送的内容,以便捕获 TypeScript 代码中的问题 - 例如您发现的问题。这将阻止问题在未来再次发生(尽管不检查提供的 JSON 是否与接口匹配)......下面的示例假设result
当前具有该any
类型。
interface NameYourResult {
dateOfBirth: string;
}
var r: NameYourResult = result;