Skip to content
Advertisement

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

Advertisement

Answer

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()));
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement