UNPKG

1.76 kBTypeScriptView Raw
1import type { ConstructableDate, ContextFn, DateArg } from "./types.js";
2/**
3 * @name constructFrom
4 * @category Generic Helpers
5 * @summary Constructs a date using the reference date and the value
6 *
7 * @description
8 * The function constructs a new date using the constructor from the reference
9 * date and the given value. It helps to build generic functions that accept
10 * date extensions.
11 *
12 * It defaults to `Date` if the passed reference date is a number or a string.
13 *
14 * Starting from v3.7.0, it allows to construct a date using `[Symbol.for("constructDateFrom")]`
15 * enabling to transfer extra properties from the reference date to the new date.
16 * It's useful for extensions like [`TZDate`](https://github.com/date-fns/tz)
17 * that accept a time zone as a constructor argument.
18 *
19 * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
20 *
21 * @param date - The reference date to take constructor from
22 * @param value - The value to create the date
23 *
24 * @returns Date initialized using the given date and value
25 *
26 * @example
27 * import { constructFrom } from "./constructFrom/date-fns";
28 *
29 * // A function that clones a date preserving the original type
30 * function cloneDate<DateType extends Date>(date: DateType): DateType {
31 * return constructFrom(
32 * date, // Use constructor from the given date
33 * date.getTime() // Use the date value to create a new date
34 * );
35 * }
36 */
37export declare function constructFrom<
38 DateType extends Date | ConstructableDate,
39 ResultDate extends Date = DateType,
40>(
41 date: DateArg<DateType> | ContextFn<ResultDate> | undefined,
42 value: DateArg<Date> & {},
43): ResultDate;