-
Notifications
You must be signed in to change notification settings - Fork 12.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
TS is overly picky when declaring a class constructor type #29707
Comments
In the pull request the rest parameter of
Not saying it should be but this is the expected behavior, |
Agree, |
@RyanCavanaugh So the issue seems ridiculously easy to fix (and I have the code ready), I was just wondering how to go about the tests. Should I add a new one or change one to include a version with |
@dragomirtitian no preference; whichever's easiest for you |
@RyanCavanaugh I added a fix, just one problem (which unfortunately probably makes my fix almost useless). The constraint class Base {
constructor(public x: number, public y: number) {}
}
let c : new (...args: unknown[]) => {} = Base // error under strictFunctionTypes: true
new c("") // runtime type mismatch This means that you can't really call the mixin with anything but an empty constructor or one that has |
That's why it's a constraint (not a concrete type) though, right? |
@RyanCavanaugh I can look into that, but this problem seems much bigger than mixins and would have implications broadly. Rest parameters of type function test<T extends (...a: unknown[]) => unknown>(fn:T) : T{
fn(""); // this passes "" can be assigned to unknown
return fn;
}
test(function (a: number) { // error here under strictFunctionTypes
}) I'm not 100% sure it is necessarily a great idea to make the code above error free . It seems to be weaker as far as type safety goes. As we see in the code above the callback passed in accepts a While this is no worse than if we use |
The problem isn't specific to constructors or rest parameters, it's just that function types are contravariant in their parameter types. You only run into this inverted subtyping relation when you, for example, pass a function as a parameter to another function, as you do with mixins.
I ran into this problem today when I needed to describe a type that would fit the right operand of |
TypeScript Version: 3.4.0-dev.20190202
Search Terms: class, extend, constructor, any[]
Code
Expected behavior:
I should be able to replace
...args: any[]
with...args: unknown[]
, or any other signature.Actual behavior:
Playground Link: https://www.typescriptlang.org/play/index.html#src=type%20ClassConstructor%20%3D%20new(...args%3A%20unknown%5B%5D)%20%3D%3E%20%7B%7D%0D%0A%0D%0Afunction%20mixin%3CC%20extends%20ClassConstructor%3E(Class%3A%20C)%20%7B%0D%0A%20%20return%20class%20extends%20Class%20%7B%7D%0D%0A%7D
The text was updated successfully, but these errors were encountered: