-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
[Proposal] Initializer syntax for function types #21572
Comments
This would fall out of scope of the design goals since it would add new expression-level syntax. Besides, Anyway, you can combine the interface declaration with interface fnWithProp {
(abc: string): string;
foo: number;
}
const o: fnWithProp = Object.assign((abc: string) => abc.toUpperCase(), { foo: 1 }); EDIT: You will need to explicitly type |
The underlying issue is tracked by #15868. there is not an easy/ergonomic way in the language to create one of these functions that have properties. the best we have today is a function and namespace combo: interface fnWithProp {
(abc: string): string;
foo: number;
}
function f(a: string) { return a; }
namespace f {
export var foo: number;
}
var abc: fnWithProp = f; |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
Using function types, it's possible to define types for functions with additional properties tacked on, e.g.
In order to initialize variables of those types, one currently has to jump through hoops because the naive attempt does not work:
By explicitly casting the function to the correct type, one can avoid the error, but now TypeScript never checks if foo is assigned (even with
strictPropertyInitialization = true
):A working version looks like this
but
abc
is now being inferred as the rather cryptic type((str: any) => any) & { foo: number }
.As an attempt to solve this problem, I propose an initializer syntax for these kinds of function types, which is similar to the object literal syntax:
or an alternative using the
this
keyword for the function body:A usage example:
The text was updated successfully, but these errors were encountered: