Repository navigation
Description
🔎 Search Terms
private constructor incompatible parameter types removed
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about private constructor type simplification
⏯ Playground Link
💻 Code
// This class doesn't exist, it is just used as a convenient way for typing any class.
declare abstract class Constructable {
private constructor(...args: unknown[]);
}
// According to generated .d.ts, this looks exact same as Constructable
abstract class GeneratedConstructable {
private constructor() {}
}
export const funcThatAcceptsAnyClass = (clazz: typeof Constructable) => {};
export const funcThatAcceptsAnyGeneratedClass = (clazz: typeof GeneratedConstructable) => {};
class MyPrivateClass {
#privateVal: boolean;
private constructor(
public readonly foo: string,
public readonly bar: string
) {
this.#privateVal = true;
}
}
class MyPrivateClassWithNoParams {
#privateVal: boolean;
private constructor() {
this.#privateVal = true;
}
}
// This is what typescript sees at build time, its passing!
funcThatAcceptsAnyClass(MyPrivateClass);
funcThatAcceptsAnyClass(MyPrivateClassWithNoParams);
// This is what typescript sees when generated files are imported elsewhere, it fails!
funcThatAcceptsAnyGeneratedClass(MyPrivateClass);
funcThatAcceptsAnyGeneratedClass(MyPrivateClassWithNoParams);🙁 Actual behavior
When a class contains a private constructor, the generated types file (.d.ts) strips the constructor down to the bare minimum, meaning any parameters are removed from the method.
This creates a type that is incompatible with the original type declaration.
Since it is only the result of generated code, it cannot be detected during build time. Instead it is caught when the types are referenced in a separate package.
🙂 Expected behavior
Either:
- Parameters are not stripped from private class constructors
- preferred
- Less likely to be breaking change
- Would produce slightly larger type files
- Private constructors are treated as parameter-less during build time
- Would not apply to "inside" the class (where private constructors can be legally called)
- Would at least produce consistent type behavior
Additional information about the issue
I stumbled across this issue when trying to restrict the type of a value to anything with a class.
Essentially the use case is a map of Class -> Instance. Restricting to "is a class" is important for instanceof checks. (I understand JS can technically call new on any function, but its 2024 and I think it is fair to restrict "class" behavior to the class keyword)
The implementation was not actually responsible for doing the instantiation, so private or abstract constructors are totally acceptable.
I have various type checks in the package itself, that behave entirely as expected.
However when I started using this package in another, suddenly I am hit with:
Argument of type 'typeof MyPrivateClass' is not assignable to parameter of type 'typeof GeneratedConstructable'.
Types of construct signatures are incompatible.
Type 'new (foo: string, bar: string) => MyPrivateClass' is not assignable to type 'abstract new () => GeneratedConstructable'.
Target signature provides too few arguments. Expected 2 or more, but got 0.
I would expect this kind of type behavior to either be caught during the original build time (second option in expected behavior) or to not implement this kind of constructor "simplifying" at all.
Perhaps it could be gated behind a compiler flag, because I can understand this is probably a fairly niche requirement. I understand in most cases, we use type comparisons against the instances, not the classes, and when using the classes a private constructor is an "internal" detail that usually does not expose it's functionality.
I would also accept an alternative to typeof Constructable.
The goal is to generate a type that effectively looks like private abstract new (...args: unknown[]) => any. However the private keyword is not allowed, and type matching fails on Cannot assign a 'private' constructor type to a 'public' constructor type
Activity
RyanCavanaugh commentedon Feb 15, 2024
I understand the presented issue, but don't really understand the use case. If you can't
newsomething yourself, then the type you're describing is justobject. Whether or not a type has internal capability to be constructed vianewis not supposed to be an externally-visible facet of the type.Andarist commentedon Feb 15, 2024
I don't understand the use case either but this is legal and it makes some convoluted sense:
JacobLey commentedon Feb 15, 2024
My use case is basically a DI-related method.
(Vastly over-simplified, but hopefully enough to get the point across).
Imagine we have a container, which is basically a map. The key is the class. The value is the instance. It is really important that we actually provide a value as the key, rather than a generic type itself, because the value is needed at runtime to be a consistent reference in the map.
The goal of this map is to be type safe. So we don't just put any class as the key and any value as the instance, we can use typescript to enforce that the instance does in fact match the class.
Example playground
In this example, it is important to me to continue to treat my
Fooclass as a construct-able class, despite the fact that the "DI framework" could care less about how it was constructed! It just needs to hold the instance offoofor future reference.If I were to fall back on generic
objecttypes, then I wouldn't be able to provide the strong typing for the return type.Note I'm aware that classes still generally follow duck typing, e.g. instances of
class Foo {}andclass Bar {}are the same to typescript, but I think that is a separate discussion. We are trying to be as type safe as possible within the realm of TS.JacobLey commentedon Feb 15, 2024
In the example I linked above, you can get around most of the issues by also using a protected class, which does not lose it's parameters on the constructor.
So the only impacted types are classes with a private constructor, and >=1 constructor parameters.
At first glance, that seems like a fairly niche classification, but I want to make the argument that private constructors are fairly common development practice.
In either of the cases above, it seems reasonable to me that we should be able to use it for my use case.
Which to re-iterate, is a method that returns an instance of the class (
getInstance). It is not necessarily performing instantiation internally, and instead is relying on previous implementation to have created the instance from somewhere.The parameter to the method should be a class, which is used as the key in the map to look up the instance. And thanks to typescript generics/inference, I can provide extra type safety that auto-types the response as an instance of the class.
However, with this current behavior, it is not possible to look up a class with a private constructor, despite the fact of how it is instantiated being irrelevant to this implementation.
To make matters worse, this behavior that private classes are not supported is not at all obvious during build time. It is not until a separate package (i.e. someone downloads this library from npm, after it is published) that they run into different, undocumented behavior. A tricky case of "it works on my machine".
Mark the workarounds with drop-when, and check the markers in verify