SlideShare una empresa de Scribd logo
1 de 25
TYPESCRIPT IS
AWESOME
LEARNING TO USE TYPESCRIPT
TYPESCRIPT IS AWESOME
WHAT IS
TYPESCRIPT
TypeScript is a
superset of
JavaScript that
compiles to clean
JavaScript output.
TYPESCRIPT IS AWESOME
FEATURES OF TYPESCRIPT
▸All valid JavaScript is valid Typescript
▸Uses Type Inference
▸Statically Typed
▸Strongly Typed
▸Duck Typed
TYPESCRIPT IS AWESOME
WHAT IS TYPE INFERENCE?
let legalDrinkingAge = 21;
if (country === ‘Canada’) {
legalDrinkingAge = 19;
};
if (country === ‘Mexico’) {
legalDrinkingAge = ’18’;
// Type '"18"' is not assignable to type 'number'
};
TYPESCRIPT IS AWESOME
WHAT IS TYPE INFERENCE?
(CONTINUED)
const sum = (num1: number, num2: number) => {
return num1 * num2;
};
const sumArray = sum(34, 132) .split();
// Property 'split' does not exist on type 'number'.
TYPESCRIPT IS AWESOME
STATICLY TYPED VS DYNAMICLY TYPED
Statically typed languages will check types at compile time - before your
program runs. Dynamic languages check during run time.
JavaScript
const myNumber = 33;
const myArray = myNumber.split();
// myNumber.split is not a function
TypeScript
const myNumber = 33;
const myArray = myNumber.split();
TYPESCRIPT IS AWESOME
WEAKLY TYPED VS STRONGLY TYPED
Strongly typed languages enforce the behavior of types and do not allow variables
to mix with variables other types easily. Weakly typed languages allow types to
change or interact with other types more easily.*
JavaScript
let myNumber = 4;
myNumber += ‘1’; //myNumber = 5
TypeScript
let myNumber = 4;
myNumber += ‘1’;
// Type 'string' is not assignable to type 'number'.
* There is no precise definition for strongly typed and weakly typed. Strong vs weak
typing is a spectrum, not an absolute.
TYPESCRIPT IS AWESOME
WHAT DOES DUCK TYPED MEAN?
“If it walks like a duck and it quacks like a duck, then it must be a duck”
interface Car {
position: number;
drive: (distance: number) => void;
};
const motorcycle = {
position: 3,
drive: (distance) => motorcycle.position += distance,
};
const moveCar = (car: Car, distance: number): void => {
car.drive(distance);
};
moveCar(motorcycle, 15); // this is allowed
TYPESCRIPT IS AWESOME
WHY YOU WON’T LIKE TYPESCRIPT
▸You will write about twice as much code
▸It is time consuming to learn and will make your personal
projects take longer to code
▸It won’t add any new bells and whistles to your applications
‣ The advantages will not be worth the cost when working on
small personal projects*
* This is my opinion. Others may disagree.
TYPESCRIPT IS AWESOME
WHY YOU SHOULD LEARN TYPESCRIPT
ANYWAY
▸Learning TypeScript will help you become a better programmer
and understand important programming concepts like interfaces,
enums, and namespaces.
▸It is easy to get started with TypeScript because you can move
your projects over from JavaScript one module at a time.
▸TypeScript is rapidly growing in popularity and is used by many
top companies.
▸You will write cleaner code that is easier for others to read and
understand.
TYPESCRIPT IS AWESOME
BASIC TYPES
Number - let speed: number = 60;
String - let name: string = ‘Keith’;
Array - let list: Array<string> = [‘1’, ‘2’, ‘3’]; let list: number[ ] = [1, 2, 3];
Tuple - let menuItem: [string, number] = [‘Lasagna’, 14.99];
Enum -
enum Success {
No = 0,
Yes = 1,
}
function respond (recipient: string, success: Success): void {
if (success) {
sendSuccessMessage(recipient);
} else {
sendFailureMessage(recipient);
}
}
respond(“Peter Gibbons”, Success.Yes);
TYPESCRIPT IS AWESOME
BASIC TYPES (CONTINUED)
Any* - let anyType: any = ‘3’; anyType = false; anyType = { a: 2, b: 3};
Void - void is usually used for returns of functions. Void can only be undefined
or sometimes null (depending on TypeScript settings**)
Null and Undefined - exactly what you would expect
let emptyVar: undefined = undefined;
let myNull: null = null;
Never - used for functions that never return
ex: function fail( ) : never { throw new Error(‘System Failure’) };
* Any is an escape hatch and should be avoided when possible
** TypeScript docs recommend using --strictNullChecks
TYPESCRIPT IS AWESOME
UNION TYPES
A union type is used when multiple types are acceptable for a variable.
Examples:
let padding: string | number;
padding = ‘5px’; // okay
padding = 5; // okay
padding = false // not okay
let menuCategory: ‘Appetizer’ | ‘Entree’ | ‘Dessert’ | ‘Side Dish’;
menuCategory = ‘Dessert’; // okay
menuCategory = ‘side dish’ // not okay
https://repl.it/@kdybvig/TypeScript-Practice
TYPESCRIPT IS AWESOME
INTERFACE
interface Animal {
position: number,
walk: (distance: number) => void;
};
interface Duck extends Animal {
quack: () => void;
};
const Daffy: Duck = {
position: 2,
walk: (distance) => Daffy.position += distance,
quack: () => console.log(‘QUACK’),
lastName: ‘Duck’,
}
TYPESCRIPT IS AWESOME
TYPE ALIAS
type Animal = {
position: number,
walk: (distance: number) => void;
};
type Duck = Animal & {
quack: () => void;
};
const Donald: Duck = {
position: 2,
walk: (distance) => Daffy.position += distance,
quack: () => console.log(‘QUACK’),
lastName: ‘Duck’,
}
TYPESCRIPT IS AWESOME
INTERFACE VS TYPE ALIAS
‣ Interfaces can only be used for objects
type suit = ‘Diamonds’ | ‘Hearts’ | ‘Spades’ | ‘Clubs’;
‣ Interfaces can be merged, types cannot
interface Cat { scratch: () => void }
interface Cat { color: string }
const tiger: Cat = {
scratch: () => console.log(‘Ouch!’),
color: ‘Orange’,
};
‣ Types are useful for unions of objects
type Pet = Cat | Dog | Hamster | Rabbit | Fish;
‣ According to the TypeScript docs we should prefer interfaces due to their
greater extensibility, but as of TypeScript 2.7 types are extensible too
TYPESCRIPT IS AWESOME
TYPES FOR FUNCTIONAL COMPONENTS
‣ State types are inferred when using useState
Example:
const [count, setCount] = useState(1);
setCount(2); // okay
setCount(‘3’) // not okay
‣ Props can be declared with either type or interface
TYPESCRIPT IS AWESOME
TYPES FOR FUNCTIONAL COMPONENTS
(CONTINUED)‣ There is also an FC (Functional Component) type built into React
‣ There is some disagreement about whether to use the FC type or
not and whether to use interface or type for props, but most
people will agree that whatever you choose you should be
consistent throughout your application
https://github.com/kmurgic/markdown-preview-app
TYPESCRIPT IS AWESOME
TYPES FOR CLASS COMPONENTS
‣ The general pattern for a React Class Component is this:
export class MyComponent extends Component<Props, State> {
TYPESCRIPT IS AWESOME
TYPES FOR CLASS COMPONENTS
‣ If a component does not have props, you can put {} for the props
type.
https://github.com/kmurgic/drum-machine-app
https://github.com/kmurgic/to-do-app
TYPESCRIPT IS AWESOME
HELPFUL RESOURCES
▸TypeScript Docs
https://www.typescriptlang.org/docs/home.html
▸How to Add TypeScript to Create React App
https://create-react-app.dev/docs/adding-typescript/
▸React TypeScript Cheatsheat
https://github.com/typescript-cheatsheets/react-typescript-
cheatsheet/blob/master/README.md
▸Ben Awad : TypeScript vs JavaScript Video
https://www.youtube.com/watch?v=D6or2gdrHRE
▸Harry Wolff: TypeScript and React Video
https://www.youtube.com/watch?v=-wBNV7i_b9o&t=399s
▸React + TypeScript Codebases to Learn From
https://github.com/typescript-cheatsheets/react-typescript-
cheatsheet/blob/master/README.md#recommended-react--typescript-
codebases-to-learn-from

Más contenido relacionado

La actualidad más candente

002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type scriptDmitrii Stoian
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practicesfelixbillon
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersRutenis Turcinas
 
QTP VB Script Trainings
QTP VB Script TrainingsQTP VB Script Trainings
QTP VB Script TrainingsAli Imran
 
Learn VbScript -String Functions
Learn VbScript -String FunctionsLearn VbScript -String Functions
Learn VbScript -String FunctionsNilanjan Saha
 
7400354 vbscript-in-qtp
7400354 vbscript-in-qtp7400354 vbscript-in-qtp
7400354 vbscript-in-qtpBharath003
 
Typescript for the programmers who like javascript
Typescript for the programmers who like javascriptTypescript for the programmers who like javascript
Typescript for the programmers who like javascriptAndrei Sebastian Cîmpean
 
Introduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston LeviIntroduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston LeviWinston Levi
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practicesIwan van der Kleijn
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painSander Mak (@Sander_Mak)
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaKnoldus Inc.
 

La actualidad más candente (20)

002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type script
 
TypeScript Best Practices
TypeScript Best PracticesTypeScript Best Practices
TypeScript Best Practices
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack Developers
 
QTP VB Script Trainings
QTP VB Script TrainingsQTP VB Script Trainings
QTP VB Script Trainings
 
TypeScript - An Introduction
TypeScript - An IntroductionTypeScript - An Introduction
TypeScript - An Introduction
 
TypeScript 2 in action
TypeScript 2 in actionTypeScript 2 in action
TypeScript 2 in action
 
Vbscript
VbscriptVbscript
Vbscript
 
Vb script
Vb scriptVb script
Vb script
 
Learn VbScript -String Functions
Learn VbScript -String FunctionsLearn VbScript -String Functions
Learn VbScript -String Functions
 
Qtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscriptQtp - Introduction to fundamentals of vbscript
Qtp - Introduction to fundamentals of vbscript
 
7400354 vbscript-in-qtp
7400354 vbscript-in-qtp7400354 vbscript-in-qtp
7400354 vbscript-in-qtp
 
Vbscript
VbscriptVbscript
Vbscript
 
Typescript for the programmers who like javascript
Typescript for the programmers who like javascriptTypescript for the programmers who like javascript
Typescript for the programmers who like javascript
 
Introduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston LeviIntroduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston Levi
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
JS - Basics
JS - BasicsJS - Basics
JS - Basics
 
Learning typescript
Learning typescriptLearning typescript
Learning typescript
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
 

Similar a Introduction to TypeScript

Type script is awesome
Type script is awesomeType script is awesome
Type script is awesomeKeithMurgic
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptEPAM Systems
 
Practical TypeScript
Practical TypeScriptPractical TypeScript
Practical TypeScriptldaws
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScriptGarth Gilmour
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyRalph Johnson
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Arthur Puthin
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScriptAleš Najmann
 
typescript.pptx
typescript.pptxtypescript.pptx
typescript.pptxZeynepOtu
 
Why Static Type Checking is Better
Why Static Type Checking is BetterWhy Static Type Checking is Better
Why Static Type Checking is BetterAndrew Rota
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type ScriptFolio3 Software
 
TypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationAndrea Paciolla
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScriptOffirmo
 

Similar a Introduction to TypeScript (20)

Type script is awesome
Type script is awesomeType script is awesome
Type script is awesome
 
Rits Brown Bag - TypeScript
Rits Brown Bag - TypeScriptRits Brown Bag - TypeScript
Rits Brown Bag - TypeScript
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScript
 
Practical TypeScript
Practical TypeScriptPractical TypeScript
Practical TypeScript
 
Type Driven Development with TypeScript
Type Driven Development with TypeScriptType Driven Development with TypeScript
Type Driven Development with TypeScript
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
 
Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
 
Introduction to typescript
Introduction to typescriptIntroduction to typescript
Introduction to typescript
 
Day 1
Day 1Day 1
Day 1
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
typescript.pptx
typescript.pptxtypescript.pptx
typescript.pptx
 
Why Static Type Checking is Better
Why Static Type Checking is BetterWhy Static Type Checking is Better
Why Static Type Checking is Better
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
TypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript application
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
 
Legacy is Good
Legacy is GoodLegacy is Good
Legacy is Good
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 

Último

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 

Último (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Introduction to TypeScript

  • 2. TYPESCRIPT IS AWESOME WHAT IS TYPESCRIPT TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
  • 3. TYPESCRIPT IS AWESOME FEATURES OF TYPESCRIPT ▸All valid JavaScript is valid Typescript ▸Uses Type Inference ▸Statically Typed ▸Strongly Typed ▸Duck Typed
  • 4. TYPESCRIPT IS AWESOME WHAT IS TYPE INFERENCE? let legalDrinkingAge = 21; if (country === ‘Canada’) { legalDrinkingAge = 19; }; if (country === ‘Mexico’) { legalDrinkingAge = ’18’; // Type '"18"' is not assignable to type 'number' };
  • 5. TYPESCRIPT IS AWESOME WHAT IS TYPE INFERENCE? (CONTINUED) const sum = (num1: number, num2: number) => { return num1 * num2; }; const sumArray = sum(34, 132) .split(); // Property 'split' does not exist on type 'number'.
  • 6. TYPESCRIPT IS AWESOME STATICLY TYPED VS DYNAMICLY TYPED Statically typed languages will check types at compile time - before your program runs. Dynamic languages check during run time. JavaScript const myNumber = 33; const myArray = myNumber.split(); // myNumber.split is not a function TypeScript const myNumber = 33; const myArray = myNumber.split();
  • 7. TYPESCRIPT IS AWESOME WEAKLY TYPED VS STRONGLY TYPED Strongly typed languages enforce the behavior of types and do not allow variables to mix with variables other types easily. Weakly typed languages allow types to change or interact with other types more easily.* JavaScript let myNumber = 4; myNumber += ‘1’; //myNumber = 5 TypeScript let myNumber = 4; myNumber += ‘1’; // Type 'string' is not assignable to type 'number'. * There is no precise definition for strongly typed and weakly typed. Strong vs weak typing is a spectrum, not an absolute.
  • 8. TYPESCRIPT IS AWESOME WHAT DOES DUCK TYPED MEAN? “If it walks like a duck and it quacks like a duck, then it must be a duck” interface Car { position: number; drive: (distance: number) => void; }; const motorcycle = { position: 3, drive: (distance) => motorcycle.position += distance, }; const moveCar = (car: Car, distance: number): void => { car.drive(distance); }; moveCar(motorcycle, 15); // this is allowed
  • 9. TYPESCRIPT IS AWESOME WHY YOU WON’T LIKE TYPESCRIPT ▸You will write about twice as much code ▸It is time consuming to learn and will make your personal projects take longer to code ▸It won’t add any new bells and whistles to your applications ‣ The advantages will not be worth the cost when working on small personal projects* * This is my opinion. Others may disagree.
  • 10. TYPESCRIPT IS AWESOME WHY YOU SHOULD LEARN TYPESCRIPT ANYWAY ▸Learning TypeScript will help you become a better programmer and understand important programming concepts like interfaces, enums, and namespaces. ▸It is easy to get started with TypeScript because you can move your projects over from JavaScript one module at a time. ▸TypeScript is rapidly growing in popularity and is used by many top companies. ▸You will write cleaner code that is easier for others to read and understand.
  • 11. TYPESCRIPT IS AWESOME BASIC TYPES Number - let speed: number = 60; String - let name: string = ‘Keith’; Array - let list: Array<string> = [‘1’, ‘2’, ‘3’]; let list: number[ ] = [1, 2, 3]; Tuple - let menuItem: [string, number] = [‘Lasagna’, 14.99]; Enum - enum Success { No = 0, Yes = 1, } function respond (recipient: string, success: Success): void { if (success) { sendSuccessMessage(recipient); } else { sendFailureMessage(recipient); } } respond(“Peter Gibbons”, Success.Yes);
  • 12. TYPESCRIPT IS AWESOME BASIC TYPES (CONTINUED) Any* - let anyType: any = ‘3’; anyType = false; anyType = { a: 2, b: 3}; Void - void is usually used for returns of functions. Void can only be undefined or sometimes null (depending on TypeScript settings**) Null and Undefined - exactly what you would expect let emptyVar: undefined = undefined; let myNull: null = null; Never - used for functions that never return ex: function fail( ) : never { throw new Error(‘System Failure’) }; * Any is an escape hatch and should be avoided when possible ** TypeScript docs recommend using --strictNullChecks
  • 13. TYPESCRIPT IS AWESOME UNION TYPES A union type is used when multiple types are acceptable for a variable. Examples: let padding: string | number; padding = ‘5px’; // okay padding = 5; // okay padding = false // not okay let menuCategory: ‘Appetizer’ | ‘Entree’ | ‘Dessert’ | ‘Side Dish’; menuCategory = ‘Dessert’; // okay menuCategory = ‘side dish’ // not okay
  • 15. TYPESCRIPT IS AWESOME INTERFACE interface Animal { position: number, walk: (distance: number) => void; }; interface Duck extends Animal { quack: () => void; }; const Daffy: Duck = { position: 2, walk: (distance) => Daffy.position += distance, quack: () => console.log(‘QUACK’), lastName: ‘Duck’, }
  • 16. TYPESCRIPT IS AWESOME TYPE ALIAS type Animal = { position: number, walk: (distance: number) => void; }; type Duck = Animal & { quack: () => void; }; const Donald: Duck = { position: 2, walk: (distance) => Daffy.position += distance, quack: () => console.log(‘QUACK’), lastName: ‘Duck’, }
  • 17. TYPESCRIPT IS AWESOME INTERFACE VS TYPE ALIAS ‣ Interfaces can only be used for objects type suit = ‘Diamonds’ | ‘Hearts’ | ‘Spades’ | ‘Clubs’; ‣ Interfaces can be merged, types cannot interface Cat { scratch: () => void } interface Cat { color: string } const tiger: Cat = { scratch: () => console.log(‘Ouch!’), color: ‘Orange’, }; ‣ Types are useful for unions of objects type Pet = Cat | Dog | Hamster | Rabbit | Fish; ‣ According to the TypeScript docs we should prefer interfaces due to their greater extensibility, but as of TypeScript 2.7 types are extensible too
  • 18. TYPESCRIPT IS AWESOME TYPES FOR FUNCTIONAL COMPONENTS ‣ State types are inferred when using useState Example: const [count, setCount] = useState(1); setCount(2); // okay setCount(‘3’) // not okay ‣ Props can be declared with either type or interface
  • 19. TYPESCRIPT IS AWESOME TYPES FOR FUNCTIONAL COMPONENTS (CONTINUED)‣ There is also an FC (Functional Component) type built into React ‣ There is some disagreement about whether to use the FC type or not and whether to use interface or type for props, but most people will agree that whatever you choose you should be consistent throughout your application
  • 21. TYPESCRIPT IS AWESOME TYPES FOR CLASS COMPONENTS ‣ The general pattern for a React Class Component is this: export class MyComponent extends Component<Props, State> {
  • 22. TYPESCRIPT IS AWESOME TYPES FOR CLASS COMPONENTS ‣ If a component does not have props, you can put {} for the props type.
  • 25. TYPESCRIPT IS AWESOME HELPFUL RESOURCES ▸TypeScript Docs https://www.typescriptlang.org/docs/home.html ▸How to Add TypeScript to Create React App https://create-react-app.dev/docs/adding-typescript/ ▸React TypeScript Cheatsheat https://github.com/typescript-cheatsheets/react-typescript- cheatsheet/blob/master/README.md ▸Ben Awad : TypeScript vs JavaScript Video https://www.youtube.com/watch?v=D6or2gdrHRE ▸Harry Wolff: TypeScript and React Video https://www.youtube.com/watch?v=-wBNV7i_b9o&t=399s ▸React + TypeScript Codebases to Learn From https://github.com/typescript-cheatsheets/react-typescript- cheatsheet/blob/master/README.md#recommended-react--typescript- codebases-to-learn-from