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?
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);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With