SlideShare a Scribd company logo
1 of 24
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 = ’21’;
};
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();
// TypeError: 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’; // TSError: Unable to compile TypeScript: 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 just my opinion. Others might 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("Princess Caroline", 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
USEFUL RESOURCES
▸TypeScript Docs
▸How to Add TypeScript to Create React App
▸React TypeScript Cheatsheat
▸TypeScript vs JavaScript Video
▸TypeScript and React Video
▸React + TypeScript Codebases to Learn From

More Related Content

What's hot

TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
Patrick John Pacaña
 

What's hot (20)

Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET Developers
 
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
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET Developers
 
Debugging an Angular App
Debugging an Angular AppDebugging an Angular App
Debugging an Angular App
 
TypeScript intro
TypeScript introTypeScript intro
TypeScript intro
 
Typescript: enjoying large scale browser development
Typescript: enjoying large scale browser developmentTypescript: enjoying large scale browser development
Typescript: enjoying large scale browser development
 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
 
Typescript - MentorMate Academy
Typescript - MentorMate AcademyTypescript - MentorMate Academy
Typescript - MentorMate Academy
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
Introduction to Angular for .NET Developers
Introduction to Angular for .NET DevelopersIntroduction to Angular for .NET Developers
Introduction to Angular for .NET Developers
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript Fundamentals
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
Functional programming in TypeScript
Functional programming in TypeScriptFunctional programming in TypeScript
Functional programming in TypeScript
 
Learning typescript
Learning typescriptLearning typescript
Learning typescript
 

Similar to Type script is awesome

Similar to Type script is awesome (20)

Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with 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
 
typescript.pptx
typescript.pptxtypescript.pptx
typescript.pptx
 
Rits Brown Bag - TypeScript
Rits Brown Bag - TypeScriptRits Brown Bag - TypeScript
Rits Brown Bag - TypeScript
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Power Leveling your TypeScript
Power Leveling your TypeScriptPower Leveling your TypeScript
Power Leveling your TypeScript
 
Typescript Basics
Typescript BasicsTypescript Basics
Typescript Basics
 
TypeScript, Dart, CoffeeScript and JavaScript Comparison
TypeScript, Dart, CoffeeScript and JavaScript ComparisonTypeScript, Dart, CoffeeScript and JavaScript Comparison
TypeScript, Dart, CoffeeScript and JavaScript Comparison
 
Flow or Type - how to React to that?
Flow or Type - how to React to that?Flow or Type - how to React to that?
Flow or Type - how to React to that?
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
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...
 
Typescript: Beginner to Advanced
Typescript: Beginner to AdvancedTypescript: Beginner to Advanced
Typescript: Beginner to Advanced
 
Type script
Type scriptType script
Type script
 
Benefits of Typescript.pptx
Benefits of Typescript.pptxBenefits of Typescript.pptx
Benefits of Typescript.pptx
 
Getting started with typescript and angular 2
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2
 
Nodejs & Typescript
Nodejs & TypescriptNodejs & Typescript
Nodejs & Typescript
 
Go1
Go1Go1
Go1
 
Practical TypeScript
Practical TypeScriptPractical TypeScript
Practical TypeScript
 
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
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
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
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Type script is awesome

  • 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 = ’21’; };
  • 5. 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(); // TypeError: myNumber.split is not a function TypeScript const myNumber = 33; const myArray = myNumber.split();
  • 6. 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’; // TSError: Unable to compile TypeScript: 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.
  • 7. 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
  • 8. 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 just my opinion. Others might disagree.
  • 9. 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.
  • 10. 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("Princess Caroline", Success.Yes);
  • 11. 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
  • 12. 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
  • 14. 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’, }
  • 15. 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’, }
  • 16. 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
  • 17. 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
  • 18. 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
  • 20. TYPESCRIPT IS AWESOME TYPES FOR CLASS COMPONENTS ‣ The general pattern for a React Class Component is this: export class MyComponent extends Component<Props, State> {
  • 21. TYPESCRIPT IS AWESOME TYPES FOR CLASS COMPONENTS ‣ If a component does not have props, you can put {} for the props type.
  • 24. TYPESCRIPT IS AWESOME USEFUL RESOURCES ▸TypeScript Docs ▸How to Add TypeScript to Create React App ▸React TypeScript Cheatsheat ▸TypeScript vs JavaScript Video ▸TypeScript and React Video ▸React + TypeScript Codebases to Learn From