-1

I want a strongly typed code. When I apply solutions from a similar question - Min/Max of dates in an array? - I get error

TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.

my code

  const min: Date = Math.min(begin as Date, (end || defaultDate) as Date);
  const max: Date = Math.max(begin as Date, (end || defaultDate) as Date);

begin as Date part is underlined.

What's the correct way of finding min/max dates in Typescript?

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259

3 Answers3

2

You can compare dates like so in typescript:

const begin: Date = new Date();
const end: Date = new Date();

const min: Date = begin < end ? begin : end;
const max: Date = begin > end ? begin : end;

The problem you were having is that Math.min returns a number.

OliverRadini
  • 6,238
  • 1
  • 21
  • 46
0

Lets say you have an array, you will map the date part by taking its getTime(), then pass it to Math.min and when you get it back, again convert it to date.

const result:number[] = array.map((item)=>new Date(item.date).getTime());
console.log(new Date(Math.min(...result)));
gorak
  • 5,233
  • 1
  • 7
  • 19
0

Thank you @OliverRadini for sample code!

My own solution, taking into account possibly nullable dates:

const begin: Date | null | undefined = // ...
const end: Date | null | undefined = // ...
const defaultDate: Date = new Date();

let min: Date;
let max: Date;
if (!begin || !end) {
  min = (begin || end || defaultDate);
  max = (begin || end || defaultDate);
} else if (begin > end) {
  min = end;
  max = begin;
} else {
  min = begin;
  max = end;
}
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259