TypeScript "strictFunctionTypes" is ignored for method syntax
- Published at
- Updated at
- Reading time
- 1min
Let's say you have this TypeScript type.
ts
typeExample = {// Method shorthand syntax (should be avoided)method (x : string | number): void// Function (or object property) syntaxfn : (x : string | number) => void;};
You might expect the function types method
and fn
to behave exactly the same, right? The only difference is that one is defined in method shorthand, whereas the other is defined in function syntax. Both accept an x
param that could either be a string
or a number
But now check this out.
ts
functionfn (x : string) { /* ... */ }constexample :Example = {// this is "fine" (but shouldn't be)...method :fn ,// this is erroring correctly...Type '(x: string) => void' is not assignable to type '(x: string | number) => void'. Types of parameters 'x' and 'x' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.2322Type '(x: string) => void' is not assignable to type '(x: string | number) => void'. Types of parameters 'x' and 'x' are incompatible. Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.: fn fn ,};
If you create an example
object whose properties don't match the Example
type, only the function syntax will detect the type mismatch. What's going on?
Apparently, there's a strictFunctionTypes
TypeScript config option (part of TypeScript's strict
config) that only works for the function syntax for legacy reasons.
During development of this feature, we discovered a large number of inherently unsafe class hierarchies, including some in the DOM. Because of this, the setting only applies to functions written in function syntax, not to those in method syntax:
The TypeScript devs purposefully turned off a type check feature for legacy reasons. Wild!
It's good to avoid the method syntax altogether and if you use TypeScript ESLint, there's a rule for it.
Join 5.7k readers and learn something new every week with Web Weekly.