Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

Let's say you have this TypeScript type.

ts
type Example = {
// Method shorthand syntax (should be avoided)
method(x: string | number): void
// Function (or object property) syntax
fn: (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
function fn(x: string) { /* ... */ }
 
const example: Example = {
// this is "fine" (but shouldn't be)...
method: fn,
// this is erroring correctly...
fn: fn,
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'.
};

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.

If you enjoyed this article...

Join 5.7k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles