Typescript intro
step 0. [Set-ExecutionPolicy RemoteSigned -Scope CurrentUser] //use this commend when you get message running scripts is disabled. first run power-shell as a administrator.
step1 install tsc/typescript globally
- npm install -g typescript
//after installation initialize an empty node.js project with typescript
- :-mkdir fileName
- :-cd fileName
step2 intialize a empty node.js project with typescripts
- npm init -y
- npx tsc --init
step3 create a a.ts file
- const x: number = 1;
- console.log(x);
step4 compile the ts file to js file
- tsc -b
difference between type scripts and Javascript
typescript is strongly
js is loosely
//in typeScript
const x : number = 20;
console.log(x);
//in javaScript
/*
const x = 20;
console.log(x);
*/
//write hello world in typescript
// write a function to calculate sum of two number
function val(a:number, b:number) {
return a + b;
}
let sum = val(4,5);
console.log("sum is" + sum);
// Create a function that takes another function as input, adn runs it after 1 second.
function runAfter15(fn: () => void) {
setTimeout(fn, 1000);
}
runAfter15(function () {
console.log("hi there");
})
//User of Interfaces to specific the type on function to avoid DRY rule
//voiliting the DRY rule
/*
function isLegal(user: {
firstName : string;
lastName: string;
age: number
}) :boolean {
if (user.age > 18) {
return true;
} else {
return false;
}
}
function thankyou(user: {
firstName : string;
lastName: string;
age: number
}) :boolean {
if (user.age > 18) {
return true;
} else {
return false;
}
}
let a : boolean = thankyou({
firstName: "dhrup",
lastName: "sinha",
age: 33
})
console.log(a);
*/
//=============================
// preventing to violate dry rule
interface User {
firstName : string;
lastName: string;
age: number
}
function isLegal(user: User):boolean {
if (user.age > 18) {
return true;
} else {
return false;
}
}
function greet(user: User) {
if (user.age > 18) {
return true;
} else {
return false;
}
}
let a : boolean = isLegal({
firstName: "dhrup",
lastName: "sinha",
age: 33
})
console.log(a);
//Here's an example of how to use interfaces in TypeScript:
```typescript
// Define an interface for a person
interface Person {
firstName: string;
lastName: string;
age?: number; // Optional property
greet(): string;
}
// Function that takes a Person as input
function introducePerson(person: Person) {
console.log(`Hello, my name is ${person.firstName} ${person.lastName}. ${person.greet()}`);
}
// Create an object that implements the Person interface
const johnDoe: Person = {
firstName: "John",
lastName: "Doe",
greet() {
return "Nice to meet you!";
}
}
// Use the function with the object
introducePerson(johnDoe); // Output: "Hello, my name is John Doe. Nice to meet you!"
```
**Explanation:**
1. **`interface Person`:**
- Declares a 'contract' that any object labeled as a `Person` must follow.
- Includes required properties (`firstName`, `lastName`)
- Includes an optional property (`age`) marked with `?`.
- Defines the signature of the method `greet`.
2. **`introducePerson` Function:**
- Takes a parameter `person` and specifies that it must be of type `Person`. This ensures the function can safely use properties and methods defined in the interface.
3. **`johnDoe` Object:**
- Implements the `Person` interface, providing the required properties and a `greet` method.
4. **`introducePerson(johnDoe)`:**
- Passes the `johnDoe` object to the function. TypeScript verifies that the object conforms to the `Person` interface.
**Key Points:**
* **Interfaces define structure:** They establish what properties and methods an object should have.
* **Type Safety:** Interfaces guarantee that objects used in certain parts of your code match that expected structure, preventing potential errors.
* **Flexibility:** You can have multiple objects with different implementations as long as they adhere to the interface.
**Would you like to see examples of interfaces with inheritance or using them with classes?**
```typescript
// Define an interface for a person
interface Person {
firstName: string;
lastName: string;
age?: number; // Optional property
greet(): string;
}
// Function that takes a Person as input
function introducePerson(person: Person) {
console.log(`Hello, my name is ${person.firstName} ${person.lastName}. ${person.greet()}`);
}
// Create an object that implements the Person interface
const johnDoe: Person = {
firstName: "John",
lastName: "Doe",
greet() {
return "Nice to meet you!";
}
}
// Use the function with the object
introducePerson(johnDoe); // Output: "Hello, my name is John Doe. Nice to meet you!"
```
**Explanation:**
1. **`interface Person`:**
- Declares a 'contract' that any object labeled as a `Person` must follow.
- Includes required properties (`firstName`, `lastName`)
- Includes an optional property (`age`) marked with `?`.
- Defines the signature of the method `greet`.
2. **`introducePerson` Function:**
- Takes a parameter `person` and specifies that it must be of type `Person`. This ensures the function can safely use properties and methods defined in the interface.
3. **`johnDoe` Object:**
- Implements the `Person` interface, providing the required properties and a `greet` method.
4. **`introducePerson(johnDoe)`:**
- Passes the `johnDoe` object to the function. TypeScript verifies that the object conforms to the `Person` interface.
**Key Points:**
* **Interfaces define structure:** They establish what properties and methods an object should have.
* **Type Safety:** Interfaces guarantee that objects used in certain parts of your code match that expected structure, preventing potential errors.
* **Flexibility:** You can have multiple objects with different implementations as long as they adhere to the interface.
**Would you like to see examples of interfaces with inheritance or using them with classes?**
// Here's an example of a class in TypeScript with explanations:
```typescript
class Person {
// Properties (fields) with type annotations
name: string;
age: number;
// Constructor with typed parameters
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
// Method with optional parameter and return type
greet(message?: string): string {
return message ? `${message}, ${this.name} says hello!` : `Hello, my name is ${this.name}.`;
}
}
// Using the class
const johnDoe = new Person("John Doe", 30);//creating and instantiated
console.log(johnDoe.greet()); // Output: "Hello, my name is John Doe."
console.log(johnDoe.greet("Hi there")); // Output: "Hi there, John Doe says hello!"
```
**Explanation:**
1. **`class Person`:** Defines a blueprint for creating objects representing people.
2. **Properties:**
- `name: string` and `age: number` define the characteristics of a `Person` object with their expected data types.
3. **Constructor:**
- A special method called with `new` to create a new `Person` object.
- `name` and `age` are the parameters used to initialize the object's properties.
- `this` refers to the current instance of the `Person` class.
4. **Method:**
- `greet(message?: string): string` defines a method named `greet`.
- It takes an optional parameter `message` of type `string`.
- It returns a string value (`: string`).
- The method uses conditional logic to construct the greeting message based on the presence of the `message` parameter.
**Using the Class:**
- `const johnDoe = new Person("John Doe", 30);` creates a new object of type `Person` with the name "John Doe" and age 30.
- `console.log(johnDoe.greet());` calls the `greet` method on the `johnDoe` object without any argument, resulting in the default greeting.
- `console.log(johnDoe.greet("Hi there"));` calls the `greet` method with the argument "Hi there", resulting in a personalized greeting.
**Key TypeScript Features:**
* **Type Annotations:** Improve code readability and maintainability by specifying data types for properties and parameters.
* **Optional Parameters:** Provide flexibility by allowing methods to accept optional arguments.
* **Return Types:** Clearly define the expected output of methods.
This is a basic example, but it demonstrates how classes in TypeScript offer structure, data encapsulation (private properties are possible), and behavior definition through methods. Let me know if you'd like to see more advanced examples like inheritance or interfaces used with classes!
```typescript
class Person {
// Properties (fields) with type annotations
name: string;
age: number;
// Constructor with typed parameters
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
// Method with optional parameter and return type
greet(message?: string): string {
return message ? `${message}, ${this.name} says hello!` : `Hello, my name is ${this.name}.`;
}
}
// Using the class
const johnDoe = new Person("John Doe", 30);//creating and instantiated
console.log(johnDoe.greet()); // Output: "Hello, my name is John Doe."
console.log(johnDoe.greet("Hi there")); // Output: "Hi there, John Doe says hello!"
```
**Explanation:**
1. **`class Person`:** Defines a blueprint for creating objects representing people.
2. **Properties:**
- `name: string` and `age: number` define the characteristics of a `Person` object with their expected data types.
3. **Constructor:**
- A special method called with `new` to create a new `Person` object.
- `name` and `age` are the parameters used to initialize the object's properties.
- `this` refers to the current instance of the `Person` class.
4. **Method:**
- `greet(message?: string): string` defines a method named `greet`.
- It takes an optional parameter `message` of type `string`.
- It returns a string value (`: string`).
- The method uses conditional logic to construct the greeting message based on the presence of the `message` parameter.
**Using the Class:**
- `const johnDoe = new Person("John Doe", 30);` creates a new object of type `Person` with the name "John Doe" and age 30.
- `console.log(johnDoe.greet());` calls the `greet` method on the `johnDoe` object without any argument, resulting in the default greeting.
- `console.log(johnDoe.greet("Hi there"));` calls the `greet` method with the argument "Hi there", resulting in a personalized greeting.
**Key TypeScript Features:**
* **Type Annotations:** Improve code readability and maintainability by specifying data types for properties and parameters.
* **Optional Parameters:** Provide flexibility by allowing methods to accept optional arguments.
* **Return Types:** Clearly define the expected output of methods.
This is a basic example, but it demonstrates how classes in TypeScript offer structure, data encapsulation (private properties are possible), and behavior definition through methods. Let me know if you'd like to see more advanced examples like inheritance or interfaces used with classes!
//Type and interfaces are almost similar to aggregate data
//when you want to check is string or number in interface and type
//interface GreeArg = number | string; //this will not allow in interfaces
//type GreeArg = number | string; //this will allow in type
interface user2 {
firstName : string;
lastName: string;
age: number
}
type user = {
firstName : string;
lastName: string;
age: number
}
//Union
// what if you want to create a type that has every property of multiple types / interfaces you can't use interfaces
type Employee = {
name:string;
startDate:Date;
}
type Manager = {
name:string;
department:string;
}
type TechLead = Employee & Manager;
const t: TechLead = {
name: " dhrup",
startDate: new Date(),
department: "adfdf"
}
.//



Comments