All Articles

Method Shorthand Syntax Considered Harmful

Matt Pocock
Matt PocockMatt is a well-regarded TypeScript expert known for his ability to demystify complex TypeScript concepts.

You might have noticed that there are two ways you can annotate a function on an object in TypeScript.

ts
interface Obj {
// Method shorthand syntax
version1(param: string): void;
// Object property syntax
version2: (param: string) => void;
}

They look very innocuous. But there's a subtle difference between the two. And thanks to a tweet from my friend Andarist, I can now say that method shorthand syntax should be avoided in almost all cases.

Why Is Method Shorthand Syntax Bad?

Using the method shorthand syntax can result in runtime errors. This is for a complicated reason, but I'll try to explain it as best as I can.

Let's say we declare a Dog interface with a barkAt method.

ts
interface Dog {
barkAt(dog: Dog): void;
}

It turns out that when you use Dog to type a variable, you can annotate the parameter for .barkAt with a narrower type than the Dog interface expects:

ts
interface SmallDog extends Dog {
// Only small dogs whimper in this universe
whimper: () => void;
}
 
const brian: Dog = {
barkAt(dog: SmallDog) {},
};

Here, we've made it so brian only wants to bark at small dogs, which have an extra .whimper() method.

This might look fine, but we're actually on the verge of a runtime error that TypeScript won't catch. Inside brian's barkAt function we could easily call dog.whimper().

ts
const brian: Dog = {
barkAt(smallDog: SmallDog) {
smallDog.whimper();
},
};

Then, we could declare a new dog - just a normal one without a whimper method:

ts
const normalDog: Dog = {
barkAt() {},
};

But when we pass the normal dog to brian.barkAt, it will fail at runtime:

ts
brian.barkAt(normalDog); // runtime error here!

It'll try to call .whimper() on normalDog, which doesn't exist. And our app will blow up.

So this is TypeScript failing to prevent a runtime error. And it's all because of the method shorthand syntax.

How Do We Fix This?

If we use object property syntax to define the method, TypeScript will throw an error if we try to assign a narrower type to the method:

ts
interface Dog {
// 1. We change it to an object property syntax...
barkAt: (dog: Dog) => void;
}
 
interface SmallDog extends Dog {
whimper: () => void;
}
 
const brian: Dog = {
// 2. ...and now it errors!
barkAt(dog: SmallDog) {},
Type '(dog: SmallDog) => void' is not assignable to type '(dog: Dog) => void'. Types of parameters 'dog' and 'dog' are incompatible. Property 'whimper' is missing in type 'Dog' but required in type 'SmallDog'.2322Type '(dog: SmallDog) => void' is not assignable to type '(dog: Dog) => void'. Types of parameters 'dog' and 'dog' are incompatible. Property 'whimper' is missing in type 'Dog' but required in type 'SmallDog'.
};

This is more in line with what we expect.

Is It Something To Do With Arrow Functions?

A common misconception is that the syntax above refers to arrow functions vs function declarations. This is not the case. Both syntaxes can be used with arrow functions or function declarations.

ts
interface Obj {
methodShorthand(param: string): void;
objectProperty: (param: string) => void;
}
 
function functionDeclaration(param: string) {}
const arrowFunction = (param: string) => {};
 
const examples: Obj[] = [
{
// You can pass arrow functions to method shorthands...
methodShorthand: arrowFunction,
// ...and vice versa
objectProperty: functionDeclaration,
},
{
methodShorthand: functionDeclaration,
objectProperty: arrowFunction,
},
];

As you can see, the syntax does not restrict whether you can use a function declaration or arrow function.

Would This Work With Types Instead Of Interfaces?

I've used interface in the example above, but the same problem occurs with type:

ts
type Dog = {
barkAt(dog: Dog): void;
};
 
type SmallDog = {
whimper: () => void;
} & Dog;
 
const brian: Dog = {
barkAt(smallDog: SmallDog) {
smallDog.whimper();
},
};
 
const normalDog: Dog = {
barkAt() {},
};
 
brian.barkAt(normalDog); // runtime error here!

Why Does This Happen?

This happens because the method shorthand syntax is bivariant. This means that the method can accept a type that is both narrower and wider than the original type.

This is not the case with the object property syntax. It only accepts a type that is narrower than the original type.

It's this unexpected bivariance that can lead to runtime errors.

The ESLint Rule

If you want to avoid this problem, you can use the ESLint rule @typescript-eslint/method-signature-style. This rule will enforce the use of the object property syntax for method signatures.

json
{
"rules": {
"@typescript-eslint/method-signature-style": [
"error",
"property"
]
}
}

So, if you're seeing an error like...

Shorthand method signature is forbidden. Use a function property instead.

...it's because you're using the method shorthand syntax, and some clever person has set up this rule to prevent you from doing so.

Are There Any Use Cases?

The reason this exists in TypeScript is because, very occasionally, you want to allow bivarance on function declarations. I'm going to cop to the fact that I'm not quite sure what those reasons are.

Michael Arnaldi, one of the authors of EffectTS, seemed to have a good read on the situation in this thread.

Matt's signature

Share this article with your friends

`any` Considered Harmful, Except For These Cases

Discover when it's appropriate to use TypeScript's any type despite its risks. Learn about legitimate cases where any is necessary.

Matt Pocock
Matt Pocock

No, TypeScript Types Don't Exist At Runtime

Learn why TypeScript's types don't exist at runtime. Discover how TypeScript compiles down to JavaScript and how it differs from other strongly-typed languages.

Matt Pocock
Matt Pocock

Deriving vs Decoupling: When NOT To Be A TypeScript Wizard

In this book teaser, we discuss deriving vs decoupling your types: when building relationships between your types or segregating them makes sense.

Matt Pocock
Matt Pocock

NoInfer: TypeScript 5.4's New Utility Type

Learn how TypeScript's new utility type, NoInfer, can improve inference behavior by controlling where types are inferred in generic functions.

Matt Pocock
Matt Pocock