eestein eestein - 29 days ago 8
TypeScript Question

Typescript not recognizing Date as Date?

I don't know what's going on here... but apparently TS is not recognizing Date as Date, instead it thinks it is a string.

Here's the code I use to save the

Date
:

var validUntil = new Date();

validUntil.setSeconds(validUntil.getSeconds() + tokenResponse.expires_in);
tokenResponse.valid_until = validUntil;


And this is my
TokenResponse
class:

export class TokenResponse {
access_token: string;
token_type: string;
expires_in: number;
valid_until: Date;
error: string;
error_description: string;
}


And here is where the exception is thrown:

userToken && userToken.valid_until.getTime() >= new Date().getTime()


Here's the exception:

enter image description here

Any ideas on what's wrong?

Thanks!

EDIT

By the way, I don't think it's related to Date variable works, but functions on it do not since I'm creating a new
Date

Answer

In code that isn't posted here, the value of userToken.validUntil is being set as a string. You will see that if you check typeof userToken.validUntil before the part of the code where calling getTime() errors.

Make sure when setting userToken.validUntil that you always assign a Date object to it. If you're deserializing JSON to userToken, then make sure the deserializer converts date strings to date objects or for a quick fix do (though not recommended):

userToken.validUntil = new Date(userToken.validUntil as any);

Note the following:

var o = { d: new Date() };
localStorage.setItem("test", JSON.stringify(o));
o = JSON.parse(localStorage.getItem("test"));
typeof o.d === "string"; // true