Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying array as arguments to Date constructor

Tags:

typescript

I am trying to construct a Date from a string[] with a variable number of elements -- sometimes 3, sometimes 6. However, the following Typescript code fails to compile:

const parts = ['1', '1', '2001'];
const dte = Date.apply(undefined, parts) as Date;

with:

Argument of type 'string[]' is not assignable to parameter of type '[]'.ts(2345)

Presumably the compiler is trying the Date constructor with no arguments, which I don't want. But even if the array is number[], the compiler doesn't seem to find the right overload:

const parts1 = parts.map(x => parseInt(x,10));
dte = Date.apply(undefined, parts1) as Date;

How can I resolve this?

More specifically, how can I create a Date using the array of values as arguments to the constructor?

like image 307
Zev Spitz Avatar asked Mar 05 '23 21:03

Zev Spitz


2 Answers

First, make sure you use numbers instead of strings. That's what the type signature says.

[1, 1, 2001]

Then, tell TypeScript what you just told us — that your list is not just any list of numbers (number[]), but a list of precisely 3 items or more.

type Sequence<T> = [T, T, T, ...T[]];

const parts: Sequence<number> = [1, 1, 2001];

All you need to do is create a new Date.

const dte = new Date(...parts);
like image 97
Karol Majewski Avatar answered Mar 15 '23 22:03

Karol Majewski


The problem is that Date constructor expects anywhere between 2 and 7 arguments. Since you are mapping an array with unknown size, you need to make sure that there are indeed specified number of args by providing defaults for the first 2. The snippet below should do the trick:

// Date constructor can have between 2 and 7 args
type DateArgs =
    [number, number, number?, number?, number?, number?, number?];

const parts = ['2000', '10', '10']
const args: DateArgs = [0, 0];
parts.forEach((part, index) => {
    args[index] = parseInt(part, 10);
})

console.log(new Date(...args));
like image 24
Dmitriy Avatar answered Mar 15 '23 23:03

Dmitriy