// extends er maddome apni bole dite parben je ai value gula chara onno kono value // accept korbe na ai function a tar jonno apnake extends kore type bole dite hobe // niche example dewa ace.// My Info TypetypeMyInfoType={name: string;age: number;salary: number;}constaddMeInMyCrushMind=<TextendsMyInfoType>(myInfo: T)=>{constcrush='Madam'constnewData={
...myInfo,
crush
}returnnewData}constmyInfo: MyInfoType={name: 'Sir',age: 24,salary: 100000}constresult=addMeInMyCrushMind(myInfo)// Generic Constraints Using Key Of Part 1typePersonType={name: string;age: number;address: string;}// crate a union type using PersonTypetypePersonTypeKeys=keyofPersonType;consttest1: PersonTypeKeys='name'// Advance use case with keyof union typefunctiongetProperty<X,YextendskeyofX>(obj: X,key: Y){obj[key]}constproperty=getProperty({name: 'Mr. X',age: 24,},'name')
Asynchronous TypeScript
// Object Type PromiseinterfaceIDataType{data: string;}constmakePromise=(): Promise<IDataType>=>{returnnewPromise<IDataType>((resolve,reject)=>{constdata: IDataType='Data is Updated'if(data){resolve(data)}else{reject('Data is not Updated')}})}constgetPromiseData=async(): Promise<IDataType>=>{constdata=awaitmakePromise()returndata}// String Type PromiseconstmakePromise=(): Promise<string>=>{returnnewPromise<string>((resolve,reject)=>{constdata: string='Data is Updated'if(data){resolve(data)}else{reject('Data is not Updated')}})}constgetPromiseData=async(): Promise<string>=>{constdata=awaitmakePromise()returndata}// Fetch json Placeholder Data interfaceITodo{userId: number;id: number;title: string;completed: boolean}constgetData=async(): Promise<ITodo>=>{constresponse=fetach('https://jsonplaceholder.typicode.com/todos/1')returndata=awaitresponse.json()}constgetTodoDataasync(): Promise<void>=>{constresult=awaitgetData()}getTodoData()
Conditional Types
// a type is dependent on another typetypea=nulltypec=undefinedtyped=numbertypeb=aextendsstring ? string : null// Nested Conditional rendering typetypee=aextendsnull
? null
: cextendsnull
? undefined
: dextendsnull
? number
: nulltypeSheikhType={wife1: string,wife2: string}typeCheckProperty<T,K>=TextendskeyofSheikhType ? true : falsetypeCheckWife=CheckProperty<SheikhType,'wife1'>// Matha Kharap Kora ExampletypeBandhubi='Fatema'|'Tanjia'|'Tisa'typeRemoveBandhubi<T,R>=TextendsR ? never : TtypeCurrentBandhubi=RemoveBandhubi<Bandhubi,'Fatema'>// OutputtypeCurrentBandhubi='Tanjia'|'Tisa'
Module 4 Typescript
How to Create Class, Object , Parameter Properties
// Create ClassclassPerson{// Parameter Properties //[perameter property er maddome amra constructor er moddhe //parameter declare kore ek sathe public, private, //protected declare korte pari tar jonno alada kore ar type bole dite hobe na]constructor(publicname: string,publicage: number){}// Create Method [Class er moddhe function create korle take method bole]publicmakePerson(): string{console.log(`My name is ${this.name} and I am ${this.age} years old`)}}constperson=newPerson('Sir',24)person.makePerson()
Inheritence
// Inheritance// Person Class with common type and methodclassPerson{name: string;age: number;address: string;constructor(name: string,age: number,address: string){this.name=name;this.age=age;this.address=address;}makeSleep(hours: number): string{return`This ${this.name} will sleep for ${hours} hours`}}// Teacher Class extend by person class value and methodclassTeacherextendsPerson{designation: string;// different propertyconstructor(name: string,age: number,address: string,designation: string){super(name,age,address)this.designation=designation;}takeClasses(numOfClass: number): string{// different methodreturn`This ${this.name} will take ${numOfClass} classes`}}constteacher1=newTeacher('Naeem',24,'Dhaka','Web Developer')// Student Class extend by person class value and methodclassStudentextendsPerson{constructor(name: string,age: number,address: string){super(name,age,address)}}conststudent1=newStudent('Hafiz',24,'Dhaka')// super use kora hoyeche karon teacher & student class parent class ke extend// korche tay value access korar jonno super use kora hoyeche
Type Guards / Type Narrowing
// Keyof GuardtypeAlphaNumeric=string|number;functionadd(a: AlphaNumeric,b: AlphaNumeric): AlphaNumeric{if(typeofa==='number'&&typeofb==='number'){returna+b}returna.toString()+b.toString()}// In GuardtypeNormalUserType={name: string;}typeAdminUserType={name: string;role: 'admin';}functiongetUser(user: NormalUserType|AdminUserType): string{if('role'inuser){return`I'm an admin and my role is ${user.role}`}return`I'm a normal user`}constnormalUser: NormalUserType={name: 'Hafiz'}constadminUser: AdminUserType={name: 'Naeem',role: 'admin'}console.log(getUser(normalUser))console.log(getUser(adminUser))// instanceof Guard [class and object er moddhe guard add korar jonno use kore]classAnimal{name: string;constructor(name: string){this.name=name;}makeSound(sound: string): string{return`This ${this.name} will make ${sound} sound`}}classDogextendsAnimal{constructor(name: string){super(name)}makeBark(){return`${this.name} will bark`}}classCatextendsAnimal{constructor(name: string){super(name)}makeMeow(){return`${this.name} will meow`}}functiongetAnimal(animal: Animal): string{if(animalinstanceofDog){returnanimal.makeBark()}if(animalinstanceofCat){returnanimal.makeMeow()}returnanimal.makeSound('some')}constanimal1=newDog('Smart Dog')// instance of Dogconstanimal2=newCat('Cute Cat')// instance of Catconsole.log(getAnimal(animal1))console.log(getAnimal(animal2))
Typescript Practice
1 Convert the following JavaScript array into a TypeScript tuple
2 Write a TypeScript function that takes in two arrays of numbers as parameters. The function should compare the elements in both arrays and return a new array that contains only the elements that are present in both arrays.
3 You have an interface for Product, containing the product's id, name, price, and category. You want to filter an array of Products based on a specific criterion and value.
// Solution// Write a TypeScript generic function that takes this array, a criterion ,// and returns a new array containing only the products that match the // given criterion and value. Use a generic type parameter in the function // signature to ensure type safety.interfaceProduct{id: number;name: string;price: number;category: string;}constproductsArray: Product[]=[{id: 1,name: "Product 1",price: 10,category: "Mobile"},{id: 2,name: "Product 2",price: 20,category: "Laptop"},{id: 3,name: "Product 3",price: 30,category: "Mobile"},{id: 4,name: "Product 4",price: 40,category: "Mac Book"},];constfilterProductsByCriterion=<TextendskeyofProduct>(products: Product[],criterion: T,value: Product[T]): Product[]=>{returnproductsArray.filter(product=>product[criterion]===value);}constresult=filterProductsByCriterion(products,"category","Mobile");console.log(result);
4 Suppose you have an array of tuples, where each tuple represents a product and contains the product name, price, and quantity. Write a TypeScript function that calculates the total cost of all the products in the array, using a generic type for the tuple and a type alias for the array.
5 Suppose you have an array of numbers in TypeScript, and you want to find the sum of all the even numbers in the array. How would you approach this problem and write code to solve it?
6 Create an interface called Person that includes properties for name (string), age (number), and email (string). Then create an array of Person objects and write a function that takes the array and a string email as parameters, and returns the Person object that matches the email or null if no match is found.
7 Create a TypeScript program that declares an array of numbers. Use the spread operator to pass the elements of the array as arguments to a function that finds the minimum and maximum values of the array. Use destructuring to assign the minimum and maximum values to separate variables, and log them to the console.
8 Create a TypeScript program that declares a function that takes a string parameter with a literal type of "red", "green", or "blue", and an optional boolean parameter. If the boolean parameter is true, log the string parameter in uppercase. If the boolean parameter is false or not provided, log the string parameter in lowercase.