Can I add a custom factory method onto DateTime? #1600
-
Suppose I had an DateTime class with custom functions on it like in this example here. Now, I want to add a custom factory method that can take another class and create a DateTime instance based on certain characteristics. In our example, we are writing custom methods for converting Google's import {BigQueryTimestamp} from '@google-cloud/bigquery';
import {DateTime} from 'luxon';
declare module 'luxon/src/datetime' {
export interface DateTimeConstructor {
fromBigQueryTimestamp(bqt: BigQueryTimestamp): DateTime;
}
export interface DateTime {
fromBigQueryTimestamp(bqt: BigQueryTimestamp): DateTime;
toBigQueryTimestamp(): BigQueryTimestamp;
}
}
DateTime.prototype.toBigQueryTimestamp = function (
this: DateTime,
): BigQueryTimestamp {
return new BigQueryTimestamp(this.toJSDate());
};
// @ts-expect-error TS2339: Property 'fromBigQueryTimestamp' does not exist on type 'typeof DateTime'.
DateTime.fromBigQueryTimestamp = function (bqt: BigQueryTimestamp): DateTime {
return DateTime.fromJSDate(new Date(bqt.value));
};
export {DateTime}; This works if we ignore the error on So we can do this: import {DateTime} from "personal/luxon";
import {BigQueryTimestamp} from "@google-cloud/bigquery";
const date = (DateTime as unknown as DateTime).fromBigQueryTimestamp(new BigQueryTimestamp(new Date()));
console.log(date); So obviously |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Personally, I would stay far away from mucking around with "other people's prototypes". It has caused nothing but grief in the past (one example: https://developer.chrome.com/blog/smooshgate). function dateTimeFromBigQueryTimestamp(bqt: BigQueryTimestamp): DateTime {
// whatever
} This also makes it clear that this is your own function and not Luxon's, which has the advantage of making it clearer to understand for other people reading your code. They won't be expecting documentation for this function in Luxon's documentation, but yours. |
Beta Was this translation helpful? Give feedback.
Personally, I would stay far away from mucking around with "other people's prototypes". It has caused nothing but grief in the past (one example: https://developer.chrome.com/blog/smooshgate).
Just write a plain old function:
This also makes it clear that this is your own function and not Luxon's, which has the advantage of making it clearer to understand for other people reading your code. They won't be expecting documentation for this function in Luxon's documentation, but yours.