Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
148 views
Typescript Notes
Typescript notes
Uploaded by
Aayush Gupta
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Typescript notes For Later
Download
Save
Save Typescript notes For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
148 views
Typescript Notes
Typescript notes
Uploaded by
Aayush Gupta
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Typescript notes For Later
Carousel Previous
Carousel Next
Save
Save Typescript notes For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 23
Search
Fullscreen
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 723er16i24, 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 aaa116124, 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 9123116124, 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@gmail.com". 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 1023116124, 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 1128nea, 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 123116124, 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) { 1323ent6i24, 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 1423nea, 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 1523716/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 1623116124, 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 1723erv6i24, 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 8120116124, 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 1923erv6i24, 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 20281604, 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 ave116124, 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 2an3116124, 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
Complete A Z Javascript Notes 1682741974
PDF
No ratings yet
Complete A Z Javascript Notes 1682741974
85 pages
OAuth 2 in Flutter Web Using AWS Cognito - by Muhammad Shahrukh - AWS in Plain English
PDF
No ratings yet
OAuth 2 in Flutter Web Using AWS Cognito - by Muhammad Shahrukh - AWS in Plain English
10 pages
02 - HTML and Javascript Intro
PDF
100% (1)
02 - HTML and Javascript Intro
8 pages
[FREE PDF sample] Murach s ASP NET Core MVC 1st Edition Mary Delamater ebooks
PDF
100% (6)
[FREE PDF sample] Murach s ASP NET Core MVC 1st Edition Mary Delamater ebooks
42 pages
Angular Notes
PDF
No ratings yet
Angular Notes
19 pages
Typescript Notes
PDF
No ratings yet
Typescript Notes
20 pages
Ethical Hacking Cyber Security
PDF
No ratings yet
Ethical Hacking Cyber Security
7 pages
Ethical Hacking Using Python
PDF
No ratings yet
Ethical Hacking Using Python
11 pages
01 Foot Printing Websites and Tools
PDF
No ratings yet
01 Foot Printing Websites and Tools
7 pages
Entity Framework Core Tutorials
PDF
No ratings yet
Entity Framework Core Tutorials
5 pages
Java Introduction
PDF
No ratings yet
Java Introduction
24 pages
SPA AngularJS Draft
PDF
No ratings yet
SPA AngularJS Draft
155 pages
EF Core
PDF
No ratings yet
EF Core
216 pages
Ethical Hacking Outline
PDF
No ratings yet
Ethical Hacking Outline
15 pages
Microservice Using ASP Core
PDF
No ratings yet
Microservice Using ASP Core
22 pages
Master ReactJS Part 4 MFurqan Riaz
PDF
No ratings yet
Master ReactJS Part 4 MFurqan Riaz
48 pages
Core (1 2 3)
PDF
No ratings yet
Core (1 2 3)
80 pages
Unit01 - Java Introduction
PDF
No ratings yet
Unit01 - Java Introduction
55 pages
Es 6
PDF
No ratings yet
Es 6
11 pages
4 Es6 Js Object Json
PDF
No ratings yet
4 Es6 Js Object Json
40 pages
Data Structure in Javascript
PDF
No ratings yet
Data Structure in Javascript
138 pages
Node - JS: Mendel Rosenblum
PDF
No ratings yet
Node - JS: Mendel Rosenblum
30 pages
Browser Events and Custom Events: Angular
PDF
No ratings yet
Browser Events and Custom Events: Angular
11 pages
Angularjs Is An Web Based Applicatio
PDF
No ratings yet
Angularjs Is An Web Based Applicatio
1 page
UIJAVAKIT
PDF
100% (1)
UIJAVAKIT
33 pages
Installing Material To Angular
PDF
No ratings yet
Installing Material To Angular
5 pages
(Representational State Transfer) : Roger L. Costello Timothy D. Kehoe
PDF
No ratings yet
(Representational State Transfer) : Roger L. Costello Timothy D. Kehoe
39 pages
Object Oriented Javascript: © 2013, Cognizant Technology Solutions
PDF
No ratings yet
Object Oriented Javascript: © 2013, Cognizant Technology Solutions
42 pages
3.2 Es6 OOPs
PDF
No ratings yet
3.2 Es6 OOPs
29 pages
Master ReactJS Part 6 MFurqan Riaz
PDF
No ratings yet
Master ReactJS Part 6 MFurqan Riaz
40 pages
Generate A New Component: NPN Install - G @angular/cli@latest
PDF
No ratings yet
Generate A New Component: NPN Install - G @angular/cli@latest
3 pages
Namaste Javascript
PDF
No ratings yet
Namaste Javascript
59 pages
React Js Tutorial
PDF
No ratings yet
React Js Tutorial
46 pages
Android Notes
PDF
No ratings yet
Android Notes
24 pages
Full Stack Web Development Outlines: HTML 5
PDF
100% (1)
Full Stack Web Development Outlines: HTML 5
4 pages
Angular
PDF
No ratings yet
Angular
53 pages
Maltego CE
PDF
No ratings yet
Maltego CE
4 pages
SpringBOOT PDF
PDF
No ratings yet
SpringBOOT PDF
14 pages
Microservice: Quick Start Guide
PDF
No ratings yet
Microservice: Quick Start Guide
20 pages
For Seminar On Ethical Hacking
PDF
No ratings yet
For Seminar On Ethical Hacking
30 pages
Node Cheatsheet PDF
PDF
No ratings yet
Node Cheatsheet PDF
6 pages
Angular
PDF
No ratings yet
Angular
9 pages
06 Spring Boot Spring MVC
PDF
No ratings yet
06 Spring Boot Spring MVC
22 pages
Javascript Q&a
PDF
No ratings yet
Javascript Q&a
142 pages
React Interview Questions
PDF
No ratings yet
React Interview Questions
6 pages
Chapter Six Java Web Technology
PDF
No ratings yet
Chapter Six Java Web Technology
44 pages
Linux Commands
PDF
100% (1)
Linux Commands
9 pages
Java Fresher Resume
PDF
No ratings yet
Java Fresher Resume
2 pages
What Is A Servlet?
PDF
No ratings yet
What Is A Servlet?
63 pages
Node JS Cheat Sheet + PDF Zero To Mastery
PDF
No ratings yet
Node JS Cheat Sheet + PDF Zero To Mastery
17 pages
ExpressJS For CDAC
PDF
No ratings yet
ExpressJS For CDAC
22 pages
Underscore - Js Examples
PDF
No ratings yet
Underscore - Js Examples
35 pages
Oauth2 Openid Connect
PDF
No ratings yet
Oauth2 Openid Connect
10 pages
Github Com Sudheer...
PDF
No ratings yet
Github Com Sudheer...
181 pages
Angular Material Tutorial
PDF
0% (1)
Angular Material Tutorial
17 pages
Angular Commands
PDF
No ratings yet
Angular Commands
21 pages
Angular 13@ Sudhakar Sharma899
PDF
100% (1)
Angular 13@ Sudhakar Sharma899
162 pages
32 Reactjs Interview Questions and Answers For 2019: Prepared by Devteam - Space
PDF
No ratings yet
32 Reactjs Interview Questions and Answers For 2019: Prepared by Devteam - Space
17 pages
Typescript Handbook
PDF
No ratings yet
Typescript Handbook
15 pages
00 Typescript Fundamentals All Sections
PDF
No ratings yet
00 Typescript Fundamentals All Sections
75 pages
Practical File CGM
PDF
No ratings yet
Practical File CGM
18 pages
Practical File CGM
PDF
No ratings yet
Practical File CGM
18 pages
1 Practical File CN-merged
PDF
No ratings yet
1 Practical File CN-merged
35 pages
1 Practical File CN-merged
PDF
No ratings yet
1 Practical File CN-merged
35 pages