Method Shorthand Typing
What you'll learn: How to type object methods using both shorthand notation and property function syntax.
When you define methods on objects in JavaScript, you have two syntactic options. TypeScript lets you use both, and each has slightly different typing implications.
The Two Syntaxes
Method Shorthand
The modern, concise way to define methods:
const calculator = {
add(a: number, b: number): number {
return a + b;
}
};
This looks like a regular function declaration, just inside an object. You type the parameters and return value exactly as you would for a standalone function.
Property Function Syntax
The older style that assigns a function to a property:
const calculator = {
add: (a: number, b: number): number => {
return a + b;
}
};
Or using function expressions:
const calculator = {
add: function(a: number, b: number): number {
return a + b;
}
};
Which Should You Use?
Both work identically from TypeScript's perspective. Method shorthand is generally preferred because it's cleaner and more readable. However, property function syntax can be useful when you're explicitly typing the entire object shape separately.
Think of it like two ways to build the same room: one uses a built-in design (shorthand), the other assembles pieces explicitly (property function). Both create the same result.
const user = {
name: "Alice",
greet(message: string): string {
return `${this.name} says: ${message}`;
}
};
Key Takeaway: Object methods can be typed with shorthand methodName(params): ReturnType or property function syntax methodName: (params) => ReturnType — both work identically, but shorthand is typically cleaner.