Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify return type of constructor of class in typescript

Tags:

typescript

I am trying to make class that implements Date Object but make some difference in a way where Date parses string argument without "Z" in the end like new Date("2022-01-01T00:00:00").

I succeed in making class that works well, but I want to make the variable that is made by this class inferred as Date, not LocalDate .

I tried making interface of it but failed. Have any idea to specify the return type of constructor?

(I want to remain class structure - not a function structure)

class LocalDate extends Date {
  constructor(value: number | string | Date);
  constructor(
    year: number,
    month: number,
    date?: number,
    hours?: number,
    minutes?: number,
    seconds?: number,
    ms?: number,
  );
  constructor(...args: any[]) {
    if (!args?.length) {
      super();
    } else if (args?.length === 1) {
      const value = args[0];
      typeof value === 'string' && !value.endsWith('Z') && !!new Date(value)
        ? super(
            new Date(value + 'Z').getTime() +
              new Date().getTimezoneOffset() * MINUTE_AS_MILLISECOND,
          )
        : super(value);
    } else {
      super(args[0], args[1], ...args.slice(1));
    }
  }
}

const VARIABLE = new LocalDate() // I want this to be inferred as Date
like image 682
Sue Kim Avatar asked Dec 20 '25 17:12

Sue Kim


1 Answers

Having a class constructor returning a different type than its class in TypeScript is actually impossible by design:

https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors

Constructors can’t have return type annotations - the class instance type is always what’s returned

See also microsoft/TypeScript#11588:

It is worth nothing that this pattern specifically was discussed by TC39 [...]. The main points were that subclassing semantics become strange, and the fact that new C() instanceof C === false which is frankly confusing.

It is also worth noting that ES6 class semantics allow returning any type [...], though that is not something that the committee encouraged or thought of as a good practice, it is mainly a mechanism to allow exotic objects and their users to use classes [...]

like image 170
ghybs Avatar answered Dec 23 '25 07:12

ghybs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!