Exploring TypeScript Interfaces: Methods vs. Function Properties

Exploring TypeScript Interfaces: Methods vs. Function Properties

Typescript, as a superset of JavaScript, enhances JavaScript’s capabilities, including the way we define object structures. We’re going to delve into a common misconception: What’s the difference between method signatures and function property definitions in TypeScript interfaces? We’ll break it down with some examples, and explain the subtle differences between these two ways of declaring a method in an interface: 1interface MyInterface { 2 myMethod(): void; // method 3 myMethod: () => void; // function 4} Defining methods in interfaces In Object-Oriented Programming (OOP), methods are the behaviours classes. TypeScript interfaces allow us to specify a contract for these methods. When we define a method in an interface using myMethod(): ReturnType;, we’re telling any class that implements this interface, “You need to have a method of this name, these arguments, and returns this type”. ...

January 9, 2024 · 4 min