Adding Methods to Interfaces
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 43 of 73.
TypeScript interfaces allow you to define these behaviors by including method signatures alongside property definitions.
A method signature in an interface specifies the name of a method, its parameters, and its return type, without providing the actual implementation. This creates a contract that any object conforming to the interface must fulfill:
interface Person {
name: string;
age: number;
greet(): string; // Method signature
}
let user: Person = {
name: "Alice",
age: 30,
greet() {
return `Hello, I'm ${this.name}`;
}
};The method signature greet(): string tells TypeScript that any object implementing the Person interface must have a greet method that takes no parameters and returns a string. The actual implementation can vary between different objects, but the signature must match exactly.
Challenge
EasyCreate an interface named Calculator with the following properties and methods:
brandof typestringmodelof typestringisScientificof typebooleanaddmethod that takes twonumberparameters and returns anumbergetInfomethod that takes no parameters and returns astring
Create an interface named BankAccount with the following properties and methods:
accountNumberof typestringbalanceof typenumberisActiveof typebooleandepositmethod that takes anumberparameter and returnsvoidgetBalancemethod that takes no parameters and returns anumber
Using your interfaces, create the following variables:
- Create a variable named
myCalculatorof typeCalculatorwith brand"Casio", model"FX-991EX", isScientifictrue, anaddmethod that returns the sum of its two parameters, and agetInfomethod that returns"[brand] [model]" - Create a variable named
savingsAccountof typeBankAccountwith accountNumber"SAV-12345", balance1500, isActivetrue, adepositmethod that adds the parameter to the balance, and agetBalancemethod that returns the current balance
Print the following outputs on separate lines:
- Call the
getInfomethod onmyCalculatorand print the result - Call the
addmethod onmyCalculatorwith arguments15and27, and print the result - Call the
getBalancemethod onsavingsAccountand print the result - Call the
depositmethod onsavingsAccountwith argument250 - Call the
getBalancemethod onsavingsAccountagain and print the result - Print the
isScientificproperty ofmyCalculator
Try it yourself
// TODO: Write your code here
// Create the Calculator interface with the required properties and methods
// Create the BankAccount interface with the required properties and methods
// Create the myCalculator variable of type Calculator
// Create the savingsAccount variable of type BankAccount
// Print all the required outputsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples6Typing Objects and Interfaces
Inline Object Type AnnotationsType Aliases for ObjectsIntroduction to InterfacesInterfaces vs. Type AliasesOptional & Readonly PropsExtending Interfaces and TypesAdding Methods to InterfacesRecap: Defining Object Shapes