Everyday TypeScript: Methods in Object Types
Welcome to the Methods in Object Types lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Object types and interfaces both allow functions as properties.
>
type Dog = {bark: () => string};const dog: Dog = {bark: () => 'woof',};dog.bark();Result:
'woof'
In TypeScript and JavaScript, functions stored as object properties like this are called "methods", whether they're in classes or not. This doesn't match the usual meaning of "method" in most programming languages, where "method" refers only to methods defined inside of classes. We'll use the nonstandard meaning in this course because we're talking about TypeScript and the wider JavaScript ecosystem.
TypeScript gives us a second way to define methods on object types. In the
Dogtype above, we defined a method asbark: () => string. In the version below, we define the same method asbark(): string.>
type Dog = {bark(): string};const dog: Dog = {bark: () => 'woof',};dog.bark();Result:
'woof'
>
interface Cat {meow(): string}const cat: Cat = {meow: () => 'nyan',};cat.meow();Result:
'nyan'
This way of defining methods is a bit more compact, which is nice. There are some other very minor differences between the two syntaxes, but they're not significant enough for us to discuss here. For this course, we'll consider the two equivalent.