-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Suggestion: syntax for overloading function expressions #16731
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
You can use call signature to do such things: const identity: {
<X extends string>(x: X): X;
<X extends number>(x: X): X;
} = <X>(x: X) => x; function identity<X extends string>(x: X): X;
function identity<X extends number>(x: X): X;
function identity<X>(x: X): X {
return x;
} |
Of course, thank you! |
I notice that when I only specify the call signature on the interface with no inline function parameter/return types, I get an error: {
type identity = {
(x: string): string;
(x: number): number;
}
// error: Parameter 'x' implicitly has an 'any' type
const identity: identity = (x) => x;
} I would expect the |
const identity: identity = (x: string | number) => x;
// ^^^^^^^^ [ts]
// Type '(x: string | number) => string | number' is not assignable to type 'identity'.
// Type 'string | number' is not assignable to type 'string'.
// Type 'number' is not assignable to type 'string'. I think using generic is the correct way but it seems something wrong with it. type identity = {
(x: string): string;
(x: number): number;
}
// no error as expected
const identity: identity = <T>(x: T) => x; type test = {
(x: string): string;
(x: number): number;
(x: boolean): object;
}
// expected error but passed
const test: test = <T>(x: T) => x; |
Currently it is only possible to define function overloads for function declarations.
Sometimes it is desirable to use function expressions instead of function declarations. It would be nice if the function overload feature was applicable to function expressions as well.
By function expression, I mean something like this:
The text was updated successfully, but these errors were encountered: