mightycode Newton
mightycode Newton

Reputation: 3949

Argument of type 'Date | null' is not assignable to parameter of type 'string'

I just don't get it.

I have this interface.

export interface Activity {
  id: string;
  title: string;
  date: Date | null;
  description: string;
  category: string;
  city: string;
  venue: string;  
}

and then I have this function:

  get activitiesByDate(){

    return Array.from(this.activityRegistry.values()).sort((a, b) => 
      Date.parse(a.date) - Date.parse(b.date));
  }

But I still get this error:

Argument of type 'Date | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.ts(2345)

What I do wrong then? And how to correct it?

Thank you

Upvotes: 0

Views: 7388

Answers (2)

Andrew
Andrew

Reputation: 7545

This is a consequence of typescript being super-extra-sure your code is bulletproof. In your interface you have defined the date property as possibly null.

date: Date | null;

That means in this piece of code:

Date.parse(a.date)

It is checking for two possibilities:

Date.parse(null)

or

Date.parse(<type Date>)

Both fail. Date.parse is expecting a string. In order to keep typescript happy,

you need to ensure that a.date is always a string. This means you need to account for null and you need to convert your date object to a string, while also accounting for null when doing the conversion of a date object into a string. This can be done with optional chaining and nullish coalescing

Date.parse(a.date?.toDateString() ?? new Date().toDateString) // or whatever default value you want

But that being said, Date.parse is not recommended. MDN What is your use case? Surely, there is a better way to go about implementing your intent.

Upvotes: 1

Tolumide
Tolumide

Reputation: 984

I think the error you are getting here is quite explanatory, but I would try to explain better:

Javascript's Date.parse() method parses a string representation of a Date, it's better explained on MDN.

This means that the argument type that Date.parse() accepts must be of type string. It also accepts arguments that are instances of Date (which is an object) in javascript. Date.parse() returns the number of milliseconds since January 1, 1970, 00:00:00 UTC

Examples:

console.log(new Date() instance of Date); // true
console.log(Date.parse(new Date().toString())) // gives the right answer

console.log(Date.parse("01 Jan 1970 00:00:00 GMT")) // works properly

What typescript is telling you in this case, is that you shouldn't be assigning a value whose type could be Date or null to a method that expects a value of type string.

So, what can you do? Since you know that the type of the variable Date on Activity could be of type Date | null

I would suggest you do something like this:

if(a.Date && b.Date) {
  Date.parse(a.date.toString()) - Date.parse(b.date.toString()));
}

Upvotes: 1

Related Questions