Date variable works, but functions on it do not

前端 未结 1 771
星月不相逢
星月不相逢 2021-01-01 15:12

I\'m using TypeScript 1.4 in an ASP.NET MVC 5 project.

I have a field of type Date, and it works partially:

var dob: Date = result.dateOfBirth;
alert         


        
相关标签:
1条回答
  • 2021-01-01 15:44

    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.

    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.

    interface NameYourResult {
        dateOfBirth: string;
    }
    
    var r: NameYourResult = result;
    
    0 讨论(0)
提交回复
热议问题