Functions and classes help you organize your code into reusable blocks. Functions do tasks, and classes create objects with properties and actions.
Declaring functions and classes in Typescript
function functionName(parameters): returnType { // code to run } class ClassName { propertyName: type; constructor(parameters) { // initialize properties } methodName(parameters): returnType { // code to run } }
Functions start with the function keyword, followed by a name and parentheses.
Classes use the class keyword and can have properties, a constructor, and methods.
function greet(name: string): void { console.log(`Hello, ${name}!`); }
class Person { name: string; constructor(name: string) { this.name = name; } sayHi(): void { console.log(`Hi, I'm ${this.name}`); } }
function add(a: number, b: number): number { return a + b; }
This program defines a function to multiply two numbers and a class to represent a rectangle with an area method. It prints the multiplication result and the rectangle's area.
function multiply(x: number, y: number): number { return x * y; } class Rectangle { width: number; height: number; constructor(width: number, height: number) { this.width = width; this.height = height; } area(): number { return this.width * this.height; } } console.log(multiply(4, 5)); const rect = new Rectangle(3, 7); console.log(rect.area());
Use void as the return type when a function does not return a value.
Inside classes, this refers to the current object.
Always initialize class properties in the constructor to avoid errors.
Functions perform tasks and can return results.
Classes group data and actions to create objects.
Use functions and classes to write clean, reusable code.
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
