What if you could write instructions once and use them everywhere without mistakes?
Why Declaring functions and classes in Typescript? - Purpose & Use Cases
Imagine you need to repeat the same set of instructions many times in your code, like calculating a total price or creating a user profile. Without functions or classes, you'd have to write the same lines over and over again everywhere.
Writing the same code repeatedly is slow and tiring. It's easy to make mistakes or forget to update all copies when something changes. Managing complex data without classes can become confusing and messy.
Functions let you write a set of instructions once and reuse them anytime, making your code cleaner and easier to fix. Classes help you organize related data and actions together, like a blueprint for creating many similar objects.
let price1 = 10; let price2 = 20; let total = price1 + price2; // repeated everywhere
function sum(a: number, b: number): number { return a + b; } let total = sum(10, 20);
It lets you build clear, reusable, and organized code that's easy to maintain and expand.
Think of a class as a recipe for making many cakes. Instead of writing the recipe each time, you just follow the class blueprint to create each cake (object) with its own flavor and size.
Functions save time by reusing code.
Classes organize data and behavior together.
Both make your code easier to read and maintain.
Practice
Solution
Step 1: Understand what a function does
A function is a block of code designed to perform a specific task.Step 2: Recognize the role of return values
Functions can return results after performing their task, making them reusable.Final Answer:
To perform a specific task and optionally return a result -> Option CQuick Check:
Function purpose = perform task + return result [OK]
- Confusing functions with variables
- Thinking functions only store data
- Believing functions cannot return values
greet that takes a string name and returns a string in TypeScript?Solution
Step 1: Check function parameter and return types
function greet(name: string): string { return `Hello, ${name}`; } correctly declares the parameternameas a string and the return type as string.Step 2: Verify function body returns a string
function greet(name: string): string { return `Hello, ${name}`; } returns a template string greeting thename, matching the return type.Final Answer:
function greet(name: string): string { return `Hello, ${name}`; } -> Option AQuick Check:
Correct parameter and return types = function greet(name: string): string { return `Hello, ${name}`; } [OK]
- Omitting parameter types in TypeScript
- Not returning a value when return type is declared
- Using console.log instead of return
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
return `Hi, I am ${this.name}`;
}
}
const p = new Person('Anna');
console.log(p.greet());Solution
Step 1: Understand class construction
ThePersonclass setsthis.nameto the passed argument 'Anna' in the constructor.Step 2: Analyze the greet method output
Thegreetmethod returns a string includingthis.name, which is 'Anna'.Final Answer:
Hi, I am Anna -> Option AQuick Check:
Class property set correctly = 'Hi, I am Anna' [OK]
- Forgetting to assign constructor parameter to this.name
- Expecting undefined because of missing this
- Confusing method return with console.log output
class Car {
model: string;
constructor(model) {
this.model = model;
}
display() {
console.log('Model: ' + this.model);
}
}Solution
Step 1: Check constructor parameter types
In TypeScript, constructor parameters should have type annotations; here,modellacks a type.Step 2: Verify other parts
Thedisplaymethod does not require a return type annotation since it returns void implicitly.Final Answer:
Missing type annotation for constructor parameter 'model' -> Option DQuick Check:
Constructor parameters need types = Missing type annotation for constructor parameter 'model' [OK]
- Omitting parameter types in constructors
- Thinking methods must always declare return types
- Assuming properties must be private by default
Calculator with a method add that takes two numbers and returns their sum. Which code correctly implements this with proper types and usage?Solution
Step 1: Check method declaration and types
class Calculator { add(a: number, b: number): number { return a + b; } } const calc = new Calculator(); console.log(calc.add(5, 3)); declaresaddwith parameters typed as numbers and return type number, which is correct.Step 2: Verify object creation and method call
class Calculator { add(a: number, b: number): number { return a + b; } } const calc = new Calculator(); console.log(calc.add(5, 3)); creates an instance withnew Calculator()and callsadd(5, 3), which returns 8.Final Answer:
Correct class with typed method and proper usage -> Option BQuick Check:
Typed method + new instance + correct call = class Calculator { add(a: number, b: number): number { return a + b; } } const calc = new Calculator(); console.log(calc.add(5, 3)); [OK]
- Calling class without 'new'
- Omitting parameter types
- Passing wrong argument types (like strings instead of numbers)
Ready to prove it?
Pass the test and this pattern moves unknown
