-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Typing on function behaves differently if as type, interface or on the function #43365
Comments
This is working as intended. In your no error versions you don't specify a return type for your functions, so the return type is inferred. Because the return type is inferree based on your returned value you don't get any excess properties. Then the compiler checks if your value (the function) is compatible with the annotated type of your variable ( |
I may have missed this @MartinJohns. For this example, why is the return type inferred? I thought I set it explicitly as type CustomType = { name: string }
type MyFunc = (arg: string) => CustomType;
const myFunc: MyFunc = (arg) => {
return { name: arg, extraKey: 1234 };
}; |
Because your anonymous arrow function has no type annotation for the return type:
Keep in mind that additional properties are legal in TypeScript. The excess property checks feature is often called "more of a linter feature" by the TypeScript team. |
Right, I understand that example @MartinJohns but since I am setting the type on the function constant, I'd expect it to adhere to the return type annotation: type MyFunc = (arg: string) => CustomType;
const myFunc: MyFunc; |
See also #40311 which attempts to change this |
@RyanCavanaugh thanks for linking that. Would LOVE to see that PR merged 🙏 |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
No error:
No error:
Errors:
🔎 Search Terms
Function types not erroring when using
type
orinterface
.🕗 Version & Regression Information
Version 4.2.3
Tested from version 3.3.3 to 4.2.3
⏯ Playground Link
N/A
Playground link with relevant code
💻 Code
See above
🙁 Actual behavior
Only the last example fails.
🙂 Expected behavior
All examples above should error. The function returns an object with incorrect keys.
The text was updated successfully, but these errors were encountered: