question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Suggestion: Improve type of `constructor` on the instance type of a class

See original GitHub issue

Search Terms

constructor type

Suggestion

This was previously discussed in this thread: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/36660#discussion_r304173536

I could see a possible future mechanism for this.constructor that returned the static side of the containing class without call or construct signatures (but retaining the apparent type of Function).

Currently, the type of the constructor property on most objects is Function. It has been suggested that for any class C {}, the type of the constructor property on the instance should be typeof C. However this suffers a significant drawback in that it severely limits subclasses as any subclass of C must have the same (or compatible) construct signatures as C.

Here is an example of this issue: https://www.typescriptlang.org/play/index.html#code/MYGwhgzhAEDKCuAHApgJwMLitA3gKGmjAC5oIAXVASwDsBzAbgOmAHsaLV5hzXUAKEmUq06ASlzNC5ABZUIAOjDQAvESaEAvnm15QkGAgBGmA9GQAPcshoATQ0jSns+QkdKdRGlu07deAqyI5BCkOEQeIvQANNDuwtT00JoSroRkjoHBimBi3tJyikaq0EEhCkbe2rq01qgAZmDAyHCZzjBphGwclP58pOQAniis9a0oGFgQTDU0dY3NrSZTkuk+PVw8-dBDI2PG7TNAA

Instead, I would suggest a mechanism to type constructor as all of the static members of typeof C but none of the call/construct signatures of typeof C, yet still having an apparent type of Function.

Use Cases

In @ljharb’s qs, he’d like to be able to use the constructor property of a Buffer-like object to access the isBuffer method on the constructor in a type-safe way (i.e. obj.constructor.isBuffer).

Examples

/// <reference types="node" />
function isBuffer(obj: { constructor: { isBuffer(obj: any): obj is Buffer; } }) {
  return obj.constructor.isBuffer(obj);
}
const buf = Buffer.alloc(10);
isBuffer(buf); // Buffer class would have a constructor that is `Buffer`

Workaround

There exists a possible workaround for this currently, though it is somewhat complicated:

type StaticMembers<TClass extends Function> = Pick<TClass, keyof TClass> & Function;

class Buffer extends Uint8Array {
  ...
  static isBuffer(obj: any): obj is Buffer;
  ...
}

interface Buffer {
  readonly constructor: StaticMembers<typeof Buffer>;
}

Playground link: https://www.typescriptlang.org/play/index.html#code/MYGwhgzhAEDKCuAHApgJwMLitA3gKGmjAC5oIAXVASwDsBzAbgOmAHsaLV5hzXUAKEmUq06ASlzNC5ABZUIAOjDQAvESaEAvnm15QkGAgBGmA9GQAPcshoATQ0jSns+QkdKdRGlu07deAqyI5BCkOEQeIvQANNDuwtT00JoSroRkjoHBimBi3tJyikaq0EEhCkbe2rrkAJ4ocORg5FTAALLIALZGaBAAPAAqzjCW1nYwAGLwNDxU7AB8JQAKrQDWg8Oxq8i1rABm0ENYEIsAZNBTMy3sTHi01qh7YMDIcJnDkuk+HJT+fKSwJotdpdHqofp1FD7N4oDDHeZMXT3NBPF5vEzHT7pNg-Lg8f6NZqtDrdXp9SHIaHGYYInRAA

Checklist

My suggestion meets these guidelines:

  • This wouldn’t be a breaking change in existing TypeScript/JavaScript code
    • Whether this is a breaking change needs to be tested.
  • This wouldn’t change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn’t a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript’s Design Goals.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:1
  • Comments:10 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
canonic-epicurecommented, Jun 12, 2020

This could be easily done with a macros. Then people would start using it right now, finding corner cases, making evaluation. At some point it would be clear if its good change for everyone or its someones, very specific requirement. In the 1st case this “macros” could be included in the TS core, in the 2nd - nobody cares and TS team does not have to care as well.

But TS team does not want to support macroses out of the box to allow language experiments in the user space. Instead they want to proceed through lengthy discussions, which lasts for years.

0reactions
hasezoeycommented, Nov 26, 2022

I would also be interested in this so i can generically get the static version without typeof Class everywhere, with for example:

type TypeofClass<T extends { constructor: new (...args: any[]) => any }> = T extends { constructor: infer S } ? S : never;
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to refer to instance type of an old-style constructor ...
I would do it like this: // Use to specify the properties on your final object interface IFoo { bar: string; } //...
Read more >
Constructor in Java | DigitalOcean
Constructor in java is used to create the instance of the class. Constructors are almost similar to methods except for two things -...
Read more >
Java Constructors - W3Schools
Java Constructors. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object...
Read more >
Generate a constructor quick action - Visual Studio (Windows)
In this article · Applies to: yes · What: Lets you immediately generate the code for a new constructor on a class. ·...
Read more >
Documentation - Classes - TypeScript
Constructors can't have return type annotations - the class instance type is always what's returned. Super Calls. Just as in JavaScript, if you...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found