Typescript fundamental
1. Hello World!
TypeScript is a superset of JavaScript that adds static types to the language. Let's start with a simple "Hello World" program.
Example:
console.log("Hello, World!");
To run this:
Save it as
hello.ts
.Compile it to JavaScript using the TypeScript compiler:
tsc hello.ts
.Run the generated
hello.js
file with Node.js:node hello.js
.
2. Variables, Constants, and Data Types
TypeScript supports variables and constants with explicit type annotations. Common data types include number
, string
, boolean
, any
, and more.
Variables
Use let
or const
for variables. TypeScript infers types when not explicitly declared.
Example:
let name: string = "Alice";
let age: number = 25;
let isStudent: boolean = true;
let dynamic: any = "Can be anything";
Constants
Use const
for values that won't change.
Example:
const PI: number = 3.14;
Other Data Types
null
andundefined
object
,array
,tuple
,enum
, etc. (covered later).
3. Concatenation and Interpolation
You can combine strings using concatenation (+
) or template literals for interpolation.
Concatenation:
let firstName: string = "John";
let lastName: string = "Doe";
let fullName: string = firstName + " " + lastName;
console.log(fullName); // Output: John Doe
Interpolation (using template literals):
let greeting: string = `Hello, ${firstName} ${lastName}!`;
console.log(greeting); // Output: Hello, John Doe!
4. Objects and Arrays
Objects
Objects in TypeScript can have defined types for their properties.
Example:
let person: { name: string; age: number } = {
name: "Alice",
age: 30
};
console.log(person.name); // Output: Alice
Arrays
Arrays hold multiple values of the same type.
Example:
let numbers: number[] = [1, 2, 3, 4];
let names: Array<string> = ["Alice", "Bob", "Charlie"];
console.log(numbers[0]); // Output: 1
console.log(names.length); // Output: 3
Tuples
Fixed-length arrays with specific types.
Example:
let tuple: [string, number] = ["Alice", 25];
console.log(tuple[0]); // Output: Alice
5. Relational and Equality Operators
elational operators compare values, and equality operators check for equality.
Relational Operators
<, >, <=, >=
Example:
let a: number = 10;
let b: number = 20;
console.log(a < b); // Output: true
console.log(a >= b); // Output: false
Equality Operators
== (loose equality, type coercion)
=== (strict equality, no type coercion)
!=, !==
Example:
let x: number = 5;
let y: string = "5";
console.log(x == y); // Output: true
console.log(x === y); // Output: false
6. Logical Operators
Logical operators combine conditions: && (AND), || (OR), ! (NOT).
Example:
let isAdult: boolean = true;
let hasLicense: boolean = false;
console.log(isAdult && hasLicense); // Output: false
console.log(isAdult || hasLicense); // Output: true
console.log(!isAdult); // Output: false
7. Conditional Statements
Conditional statements control the flow of execution based on conditions.
If-Else
let age: number = 18;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Output: Adult
Switch
let day: number = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Other day");
}
// Output: Tuesday
8. Loops
Loops allow repetitive execution of code.
For Loop
for (let i: number = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4
While Loop
let count: number = 0;
while (count < 3) {
console.log(count);
count++;
}
// Output: 0, 1, 2
For...of Loop (for arrays)
let fruits: string[] = ["Apple", "Banana", "Orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// Output: Apple, Banana, Orange
9. Functions
Functions in TypeScript can have typed parameters and return types.
Example:
function add(a: number, b: number): number {
return a + b;
}
console.log(add(5, 3)); // Output: 8
Optional Parameters
function greet(name: string, greeting?: string): string {
return `${greeting || "Hello"}, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet("Bob", "Hi")); // Output: Hi, Bob!
Arrow Functions
const multiply = (x: number, y: number): number => x * y;
console.log(multiply(4, 5)); // Output: 20
10. Classes and Methods
Classes define blueprints for objects with properties and methods.
Example:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
introduce(): string {
return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
}
}
let person: Person = new Person("Alice", 25);
console.log(person.introduce()); // Output: Hi, I'm Alice and I'm 25 years old.
Inheritance
class Student extends Person {
grade: number;
constructor(name: string, age: number, grade: number) {
super(name, age);
this.grade = grade;
}
study(): string {
return `${this.name} is studying.`;
}
}
let student: Student = new Student("Bob", 20, 10);
console.log(student.introduce()); // Output: Hi, I'm Bob and I'm 20 years old.
console.log(student.study()); // Output: Bob is studying.
11. Practice Exercises
Try these exercises to test your understanding of TypeScript fundamentals.
Hello World Modification Create a program that prints "Welcome to TypeScript!" to the console.
Variable Swap Declare two variables a and b with numbers, swap their values, and print the result.
String Interpolation Create a function that takes a name and age and returns a string like "Hello, [name]! You are [age] years old."
Array Sum Write a function that takes an array of numbers and returns their sum.
Object Creation Define an object type for a Car with properties brand (string) and year (number). Create an instance and print its properties.
Equality Check Write a function that checks if two numbers are equal using both == and === and explains the difference in output.
Logical Operator Task Create a function that takes age and hasLicense and returns true only if the person is over 18 and has a license.
Grade Calculator Write a program that takes a score (0-100) and prints a letter grade (A, B, C, D, F) using if-else or switch.
Loop Exercise Write a loop that prints all even numbers from 1 to 20.
Class Creation Create a Rectangle class with width and height properties and a method getArea() that returns the area. Test it with an instance.
Last updated