-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Type narrowing on Function.length for either callable type #18422
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
Comments
I don't really know whether narrowing by I think it's worth considering whether it's the common enough case though, or whether it's fair game for single-signature types. |
Ok, that makes sense. Is there a better way to express the idea of an interface that implement a method one of two ways. I also tried: interface X { x: number }
interface Y { y: number }
interface IFoo {
a(x: X): string
a(x: Y, y: boolean): string
}
const z: IFoo = {
a(x: X) { return '' }
}
if (z.a.length <= 1) {
z.a({ x: 1 })
} But this fails to compile since types |
The type system really does not have a good way to model function.length, in almost all its uses. The only way that works today is to have the signature part of type that that has a discriminant property, e.g.: type IFoo = {
kind: "x",
a(x: X): string
} | {
kind: "y"
a(x: Y, y: boolean): string
};
const z: IFoo = {
kind: "x",
a(x: X) { return '' }
};
if (z.kind === "x") {
z.a({ x: 1 })
} |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
TypeScript Version: 2.5.2
Code
Expected behavior:
Type of
z.a
is narrowed to(x: number) => string)
from the if statementActual behavior:
Error:
I'm trying to express an interface that can implement a method in one of two ways. Let me know if there is a better way to express this
The text was updated successfully, but these errors were encountered: