0% found this document useful (0 votes)
140 views

Typescript Notes

Typescript notes

Uploaded by

Aayush Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
140 views

Typescript Notes

Typescript notes

Uploaded by

Aayush Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 23
116124, 1.27 PM. DailyCose Step 1 - Types of languages 1. Strongly typed vs loosely typed The terms strongly typed and loosely typed refer to how programming languages handle types, particularly how strict they are about type conversions and type safety. Strongly typed languages © Loosely typed languages 1. Examples - Java, C++, C, Rust 1. Examples - Python, Javascript, Perl, hy 2. Benefits - pnp 2. Benefits 1. Lesser runtime errors 1. Easy to write code 2. Stricter codebase 2. Fast to bootstrap 3, Easy to catch errors at compile time 3. Low leaming curve Code doesn’t work Code does work Hinclude 18) { return true; } else { return false console. log(isLegal(2)); https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 723 er16i24, 1:27 PM DailyCose eters Problem 4 - Create a function that takes another function as input, and runs it after 1 second Y Code function delayedCall (Fi setTimeout(fn, 1000); () => void) { delayedCall(function() { console. log("hi there"); Step 5 - The tsconfig file The tscontig file has a bunch of options that you can change to change the compilation process. Some of these include nitpssprojects.100xdevs.comipatl8S8PPXGKGEQKFOTWSBmLts-1 aaa 116124, 1.27 PM. DailyCose 1. target The target option ina tsconfig.json file specifies the ECMAScript target version to which the TypeScript compiler will compile the TypeScript code. To try it out, try compiling the following code for target being ess and es2020 const greet = (name: string) => “Hello, ${name,. 5 Y Output for ESS “use strict"; var greet = function (name) { return "Hello, " . concat(name, Y Output for £52020 “use strict"; const greet = (name) -> “Hello, ${name}!*; 2. rootDir Where should the compiler look for .ts files. Good practise is for this to be the src folder 3. outDir Where should the compiler look for spit out the js files. 4, nolmplicitAny Try enabling it and see the compilation errors on the following code - Copy const greet = (name) => “Hello, ${name,. 5 Then try disabling it 5. removeComments Weather or not to include comments in the final js file https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 9123 116124, 1.27 PM. DailyCose Step 6 - Interfaces 1. What are interfaces How can you assign types to objects? For example, a user object that looks like this - Copy const user = { firstNam “harkirat”, lastName: "singh", email: "[email protected]". age: 21, To assign a type to the user object, you can use interfaces interface User { firstName: string; LastName: strings email: string; age: number; Assignment #1 - Create a function istegal that retums true or false if a user is above 18. It takes a user as an input. Y Solution interface User { firstName: string; lastName: string; email: string; https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 1023 116124, 1.27 PM. DailyCose age: number; function isLegal(user: User) { if (user.age > 18) { return true } else { return false; Assignment #2 - Create a React component that takes todos as an input and renders them. © Select typescript when init vite@latest ing the react project using npn create Y Solution /1 Todo.tsx interface Todotype { title: string; description: string; done: boolean; interface TodoInput { todo: TodoTypes function Todo({ todo }: TodoInput) { return

{todo.title)

{todo.description}

https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 1128 nea, 127M Daiycooe 2. Implementing interfaces Interfaces have another special property. You can implement interfaces as a class. Let's say you have an person interface - interface Person { name: string; age: number; greet (phrase: string): void; You can create a class which inplenents this interface. copy class Employee implements Person { name: string; age: number; constructor(n: string, a: number) { this.name = nj this.age = a greet (phrase: string) { console. log(*${phrase} ${this.name}” ); This is useful since now you can create multiple variants of a person (Manager, CEO ) Summary 1. You can use interfaces to aggregate data 2. You can use interfaces to implement classes from https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 123 116124, 1.27 PM. Step 7 - Types What are types? DaiyCode Very similar to interfaces , types let you aggregate data together. type User = { ory FirstName: string; lastName: string; age: number But they let you do a few other things 1. Unions Let's say you want to print the id ofa user, which can be a number or a string, © You can not do this using interfaces console.log(* ID: ${id}*) } printTd(161); // 1D: 161 printTd("202"); // 1D: 202 hitps:frojcts.100xdevs.com/pafl6SbPPXGKGBQKFOTWSBMLs-1 type StringOrNumber = string | numic.> function printId(id: StringOrNumber) { 1323 ent6i24, 1:27 PM DailyCose 2. Intersection What if you want to create a type that has every property of multiple types / interfaces © You can not do this using interfaces type Employee = { name: string; startDate: Date; type Manager = { name: string; department: string; ub type TeamLead = Employee & Manager; const teamlead: Teamlead = { name: “harkirat", startDate: new Date(), department: "Software developer" } Step 8 - Arrays in TS Ifyou want to access arrays in typescript, it’s as simple as adding a [] annotation next to the type https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 1423 nea, 127M Daiycooe Example 1 Given an array of positive integers as input, return the maximum value in the array Y Solution function maxValue(arr: number[]) { let max = for (let i = @; i < arr.length; i++) { if (arr[i] > max) { max = arr[i] + return max; console. log(maxValue([1, 2, 3]))5 Example 2 Given a list of users, filter out the users that are legal (greater than 18 years of age) interface User {0 FirstName: string; lastName: string; age: number; Y Solution interface User { FirstName: string; lastName: string; age: number; function filteredUsers(users: User[]) { return users.filter(x => x.age >= 18); itps:frojcts.100xdevs.com/paHl6SbPPXGKGBQKFOTWSBMLs-1 1523 716/24, 1.27 PA DalyCooe console. log(filteredUsers([{ FirstName: “harkirat", lastName: “Singh”, age: 21 be firstName: "Raman", lastName: "Singh", age: 16 % 1s Step 9 - Enums Enums (short for enumerations) in TypeScript are a feature that allows you to define a set of named constants. The concept behind an enumeration is to create a human-readable way to represent a set of constant values, which might otherwise be represented as numbers or strings. Example 1 - Game Let's say you have a game where you have to perform an action based on weather the user has pressed the up arrow key, down arrow key, left arrow key or right arrow key. function doSonething(keyPresseu, // do something. What should the type of keyPressed be? Should it be a string? ( uP , DoW , LEFT, RIGHT)? Should it be numbers? (1, https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 1623 116124, 1.27 PM. DailyCose The best thing to use in such a case is an_enun enum Direction { Up, Down, Left, Right function doSomething(keyPressed: Direction) { 71 do something. doSomething(Direction.Up) This makes code slightly cleaner to read out. © The final value stored at runtine is still a number (0, 1, 2, 3). 2. What values do you see at runtime for Direction.UP ? Try logging birection.up on screen ¥ Code enum Direction { up, Down, Left, Right function doSomething(keyPressed: Direction) { // do something. https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 1723 erv6i24, 1:27 PM DailyCose doSomething(Direction.Up) console. log(Direction.Up) node a.js This tells you that by default, enuns get values as @, 1, 2 3. How to change values? enum Direction { Up = 1, Down, // becomes 2 by default Left, // becomes 3 Right // becomes 4 function doSomething(keyPressed: Direction) { // do something. doSomething (Direction .Down) ¥ Solution Down = "Down", Left = "Left", Right = nitpssprojects.100xdevs.comipatl8S8PPXGKGEQKFOTWSBmLts-1 8120 116124, 1.27 PM. DailyCose function doSonething(keyPressed: Direction) { // do something. doSomething (Direction .Doun) 5. Common usecase in express enum Responsestatus { ey Success = 200, NotFound = 4e4, Error = 500 app.get("/", (req, res) => ( if (Ireq.query.usertd) { res.status(ResponseStatus.Error) .json({}) + // and so on res. status(ResponseStatus. Success). json({}); » Step 10 - Generics Generics are a language independent concept (exist in C++ as well) Let's learn it via an example 1. Problem Statement hitps:frojcts.100xdevs.com/pafl6SbPPXGKGBQKFOTWSBMLs-1 1923 erv6i24, 1:27 PM DailyCose Let's say you have a function that needs to return the first element of an array. Array can be of type either string or integer. How would you solve this problem? Y Solution function getFirstEleme return arr[@]5 arr: (string | number)[]) { const el = getFirstElement([1, 2, 3])5 What is the problem in this approach? ¥ User can send different types of values in inputs, without any type errors function getFirstEleme! return arr]; (arr: (string | number){]) { const el = getFirstElenent([1, 2, °3'])3 ¥ Typescript isn’t able to infer the right type of the return type function getFirstElement (arr. return arr]; (string | number)[]) const el = getFir: console. log(el tElement (["harkiratSingh", “ramanSingh"]); LowerCase()) ee ne Re rec ee ea etre a tet ee a ese nitpssprojects.100xdevs.comipatl8S8PPXGKGEQKFOTWSBmLts-1 2028 1604, 127 PM Daiycooe 2. Solution - Generics Generics enable you to create components that work with any data type while still providing compile-time type safety. Simple example - Y Code function identity(arg: T): T { return arg; let outputi = ident Jet output2 = id ty ("myString” ty(1@0) ; n identity Tacha) Tt Ta aretha lina Belk a te ee ML Se le ae let output2 = identity Cl 3. Solution to original problem Can you modify the code of the original problem now to include generics in it? function getFirstElement(arr: T[]) { return arr[@]; const el = getFirstElement(["harkiratSingh", "ramanSingh"]); console. log(el.toLowerCase()) nitpssprojects.100xdevs.comipatl8S8PPXGKGEQKFOTWSBmLts-1 ave 116124, 1.27 PM. DailyCose Did the issues go away? Y User can send different types of values in inputs, without any type errors function getFirstElement(arr: T[]) { return arr[0]; const el = getFirst€lement(["harkiratSingh", 2]); console. log(el.toLowercase()) ¥ Typescript isn’t able to infer the right type of the return type function getFirstElement(arr: TL]) { return arr[@]; const el = getFirstElement(["harkiratSingh", "ramanSingh"]); console. log(el. toLowerCase()) Step 11 - Exporting and importing modules ‘TypeScript follows the ES6 module system, using import and export statements to share code between different files. Here's a brief overview of how this works: 1. Constant exports math.ts https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 2an3 116124, 1.27 PM. DailyCose Cop export function add(x: number, y: number): number ( °PY return x + export function subtract(x: number, y: number): number { return x - y5 main.ts c import { add } from". /ma.. add(1, 2) 2. Default exports export default class Calculator ¢ “PY add(x: number, y: number): number { return x + y3 calculator.ts import Calculator from './Calculatu. const calc = new Calculator(); console. log(calc.add(10, 5))5 https:fprojects.100xdevs.com/pat!6S0PPXGKGSOKFOTWSBMLS-1 2313

You might also like