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)
256 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)
256 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 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 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
JS-A.L.U01 (Types and Coercion)
PDF
No ratings yet
JS-A.L.U01 (Types and Coercion)
92 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
Entity Framework Core Tutorials
PDF
No ratings yet
Entity Framework Core Tutorials
5 pages
Java Introduction
PDF
No ratings yet
Java Introduction
24 pages
Express JS
PDF
No ratings yet
Express JS
131 pages
Angular Notes
PDF
No ratings yet
Angular Notes
19 pages
100 Node.js Interview Questions
PDF
No ratings yet
100 Node.js Interview Questions
105 pages
JavaScript Built-In Objects
PDF
No ratings yet
JavaScript Built-In Objects
40 pages
Chapter Six Java Web Technology
PDF
No ratings yet
Chapter Six Java Web Technology
44 pages
EF Core
PDF
No ratings yet
EF Core
216 pages
OOP Javascript
PDF
No ratings yet
OOP Javascript
8 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
MongoDB
PDF
No ratings yet
MongoDB
99 pages
Introduction To Node - Js
PDF
No ratings yet
Introduction To Node - Js
21 pages
MongoDB With Example
PDF
No ratings yet
MongoDB With Example
9 pages
Arp Spoofing Final Project
PDF
No ratings yet
Arp Spoofing Final Project
71 pages
Master ReactJS Part 4 MFurqan Riaz
PDF
No ratings yet
Master ReactJS Part 4 MFurqan Riaz
48 pages
Unit-1 Java Programming
PDF
No ratings yet
Unit-1 Java Programming
54 pages
Angular Notes
PDF
No ratings yet
Angular Notes
134 pages
Lintroduction: Its Official Documentation Chrome'S Javascript Runtime
PDF
No ratings yet
Lintroduction: Its Official Documentation Chrome'S Javascript Runtime
35 pages
Node - JS: Mendel Rosenblum
PDF
No ratings yet
Node - JS: Mendel Rosenblum
30 pages
Angular Commands
PDF
No ratings yet
Angular Commands
21 pages
Make API Call in NodeJS
PDF
No ratings yet
Make API Call in NodeJS
12 pages
01 Foot Printing Websites and Tools
PDF
No ratings yet
01 Foot Printing Websites and Tools
7 pages
FullStack Presentation
PDF
No ratings yet
FullStack Presentation
19 pages
Spring 120 Boot Initilizr
PDF
No ratings yet
Spring 120 Boot Initilizr
23 pages
Mindtree Interview
PDF
No ratings yet
Mindtree Interview
2 pages
React Interview Questions
PDF
No ratings yet
React Interview Questions
6 pages
Frontend Interview
PDF
No ratings yet
Frontend Interview
164 pages
Spring MVC Final Best
PDF
No ratings yet
Spring MVC Final Best
28 pages
L48 - MongoDB
PDF
No ratings yet
L48 - MongoDB
31 pages
Git & GitHub Cheat Sheet
PDF
No ratings yet
Git & GitHub Cheat Sheet
11 pages
Introduction To Nodejs
PDF
No ratings yet
Introduction To Nodejs
7 pages
Servlet
PDF
No ratings yet
Servlet
52 pages
Top Nodejs ExpressJs IQ
PDF
No ratings yet
Top Nodejs ExpressJs IQ
58 pages
SPA AngularJS Draft
PDF
No ratings yet
SPA AngularJS Draft
155 pages
3.2 Es6 OOPs
PDF
No ratings yet
3.2 Es6 OOPs
29 pages
06 Spring Boot Spring MVC
PDF
No ratings yet
06 Spring Boot Spring MVC
22 pages
CICD Pipeline
PDF
No ratings yet
CICD Pipeline
10 pages
Pluralsight - Angular Reactive Forms
PDF
No ratings yet
Pluralsight - Angular Reactive Forms
190 pages
ES6 Notes
PDF
100% (1)
ES6 Notes
2 pages
CICD
PDF
No ratings yet
CICD
87 pages
Web Development: JAM-Geek Community
PDF
No ratings yet
Web Development: JAM-Geek Community
6 pages
Unit-1 Introduction To React and ES6 OLD
PDF
No ratings yet
Unit-1 Introduction To React and ES6 OLD
85 pages
Angular 13@ Sudhakar Sharma899
PDF
100% (1)
Angular 13@ Sudhakar Sharma899
162 pages
Rxjs Operators Slides
PDF
No ratings yet
Rxjs Operators Slides
23 pages
Microservice: Quick Start Guide
PDF
No ratings yet
Microservice: Quick Start Guide
20 pages
Node
PDF
100% (1)
Node
31 pages
Type Script
PDF
No ratings yet
Type Script
103 pages
Auth Guard in Angular
PDF
No ratings yet
Auth Guard in Angular
16 pages
Tactical Wireshark Kevin Cardwell download pdf
PDF
100% (4)
Tactical Wireshark Kevin Cardwell download pdf
76 pages
Unit01 - Java Introduction
PDF
No ratings yet
Unit01 - Java Introduction
55 pages
UIJAVAKIT
PDF
100% (1)
UIJAVAKIT
33 pages
AngularCheatSheet DNCMagazine
PDF
No ratings yet
AngularCheatSheet DNCMagazine
14 pages
Node
PDF
No ratings yet
Node
54 pages
Angularjs Is An Web Based Applicatio
PDF
No ratings yet
Angularjs Is An Web Based Applicatio
1 page
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
What is JavaScript
PDF
No ratings yet
What is JavaScript
10 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