SlideShare a Scribd company logo
An Introduction to TypeScript
The front-end React developer world is all abuzz with the fondness of using and
preferring TypeScript over JavaScript. Although it’s not recommended for all
types of projects it strongly overcomes many shortcomings of JavaScript and
improves over it.
In this beginner-friendly article, we will get to know what exactly TypeScript is,
how is it a strongly-typed language, how it compares to JavaScript along with
some of its highlighting features. Of course, we will be writing our first .ts code
too!
What is TypeScript?
TypeScript is a strongly typed programming language that builds on JavaScript
giving you better tooling at any scale. It’s a free and open-sourced project
created by Microsoft.
It is a ‘superset of JavaScript’, which means that you can continue to use the
JavaScript skills you’ve already developed and add certain features that were
previously unavailable to you. When compared to JavaScript, it’s a strongly
typed language as opposed to JS which is a loosely typed language. You can
consider this like JavaScript with superpowers!
Now here’s where this language actually shines…remember the term
‘strongly typed’ we used above? What does it mean in this context? Well, this
means that the data types of variables/functions and other primitives must
be pre-defined. This is one of the most important features of TypeScript (that’s
why it focuses so much on the ‘type’).
Under the hood, it compiles to JavaScript, giving you the benefit of the
JavaScript platform plus the intended advantages of types.
Top features of TypeScript
Now that you know a bit about this language, it’s time to see all the important
and useful features it provides to the developer. Here are a few of them:
1. JavaScript and more: TypeScript adds additional syntactic sugar to your
JavaScript code to support a tighter integration with your editor.
2. Runs anywhere where JavaScript does: TypeScript code converts to
JavaScript which can then be run in a browser, on Node.js or Deno, and in your
apps.
3. Safety with scalability: it uses type inference to give you great tooling without
writing any additional code.
4. Editor support: most of the modern IDEs and code editors like VS Code come
with built-in support for TypeScript files. You get autocompletion and auto-
import support in VS Code out of the box.
5. Unique language features: here are some of the features which you will only
find in a TypeScript code; Interfaces, Namespaces, Generics, Abstract classes,
Data modifiers, and more!
6. Gradual adoption rate: you can apply the types to any previous JavaScript
projects or codebase incrementally. With great editor support, TypeScript
catches errors right inside your editor!
7. Easy to describe the data: it’s really easy to describe the shape of objects
and functions in your code. This makes it possible to see documentation and
issues in your editor.
All of this should give you a general idea of what TypeScript is and what are its
features, it’s time to write our first TypeScript code and see how to use it with
JavaScript gradually.
From JavaScript to TypeScript
We won’t be diving straight into a TypeScript code. Instead, we want you to
get familiar with an already existing knowledge of JavaScript and use it to
convert a small JS code to TS code.
Let’s say we have the following JavaScript code:
// @ts-check
function compact (arr) {
if (orr. length > 10)
return arr. trim(0, 10)
return arr
}
Now you will see an error like “Cannot find name ‘orr‘.” Next, let’s say we
do another mistake like using
trim instead of slice on an array:
function compact (arr: string[]) {
if (arr.length > 10)
return arr.slice(0, 10)
return arr
}
We add a type of string[] (String array) for the arr parameter so it should always
accept a string-based array and nothing else. Hence, we call TypeScript
‘strongly-typed’.
Install and Setup TypeScript
Time to write some TS code locally on our machine! You can install TypeScript
globally via the following NPM command:
npm install -g typescript
Next, you can confirm the installation by running tsc –v to check the version of
TypeScript installed in your system.
Note that after you write a TypeScript code and want to run it, simply
running tsc with file, the name won’t work as tsc is just a TypeScript compiler.
We need Node.js to get the actual log output. We can do it by running this
command for a “Hello World” program:
tsc hello.ts && node hello.js
Your first“Hello World!” in TypeScript
After you installed TypeScript globally on your machine. You can open a suitable
code editor like VS Code which has excellent support for the TypeScript tooling.
1. Create a new TypeScript file called helloWorld.ts. Then simply write a console log
statement as you would do in JavaScript:
console.log("Hello World!");
2. Open your command prompt or Terminal window and run tsc helloWorld.ts. You
will see nothing will happen as there are no types assigned here hence no type
errors.
3. Instead you will see the TypeScript compiler generates a new helloWorld.js file
in the same directory. This is the same TS code but it is the generated JS file
output.
4. Time to make our console statement better. Let’s say we want to log the
person’s name and date by asking the user to enter it through a greeter
function:
function greet(person, date) {
console.log(`Hello ${person}, today is ${date}!`);
}
greet('Brendan');
Notice the way we are calling the greet function. If you run this you will get this
error because we passed only 1 argument instead of the expected 2:
// TS ERROR: Expected 2 arguments, but got 1.
The parameters to the greet() function don’t have any explicitly defined types
so TS will give it any type.
5. Let’s fix our function with the following valid code:
// "greet() takes a person of type string, and a date of type Date"
function greet(person: string, date: Date) {
console.log(`Hello ${person}, today is ${date.toDateString()}`);
}
greet('Maddison', new Date());
Now we have explicitly defined all the data types and we can happily see the log
statement printing the exact output we need.
Just in case you are wondering the equivalent JS code of this will be:
// "greet() takes a person of type string, and a date of type Date"
function greet(person, date) {
console.log("Hello " + person + ", today is " + date.toDateString() + "!");
}
greet('Maddison', new Date());
With that, we have covered the bare-minimum basics you need to know of the
TypeScript language. As you saw, it’s very much close to JavaScript so if you
were already working with JavaScript then it should be easy to learn and migrate
your projects to TypeScript. To make your work easy, we’ve created
some dashboard templates. Check out now!
Source: https://blog.wrappixel.com/introduction-to-typescript/
**********

More Related Content

Similar to An Introduction to TypeScript

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
Knoldus Inc.
 
Type script
Type scriptType script
Type script
Mallikarjuna G D
 
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
Rutenis Turcinas
 
Type script
Type scriptType script
Type script
srinivaskapa1
 
Moving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should KnowMoving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should Know
Fibonalabs
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University
 
Introjs10.5.17SD
Introjs10.5.17SDIntrojs10.5.17SD
Introjs10.5.17SD
Thinkful
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
michaelaaron25322
 
Lecture-15.pptx
Lecture-15.pptxLecture-15.pptx
Lecture-15.pptx
vishal choudhary
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
Laurent Duveau
 
Reasons to Use Typescript for Your Next Project Over Javascript.pdf
Reasons to Use Typescript for Your Next Project Over Javascript.pdfReasons to Use Typescript for Your Next Project Over Javascript.pdf
Reasons to Use Typescript for Your Next Project Over Javascript.pdf
MobMaxime
 
Csharp_Chap01
Csharp_Chap01Csharp_Chap01
Csharp_Chap01
Mohamed Krar
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
Laurent Duveau
 
Migrating Web SDK from JS to TS
Migrating Web SDK from JS to TSMigrating Web SDK from JS to TS
Migrating Web SDK from JS to TS
Grigory Petrov
 
CSC PPT 12.pptx
CSC PPT 12.pptxCSC PPT 12.pptx
CSC PPT 12.pptx
DrRavneetSingh
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
C# 6.0
C# 6.0C# 6.0
C# 6.0
Paul Graham
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
維佋 唐
 
js.pptx
js.pptxjs.pptx
js.pptx
SuhaibKhan62
 
You should Know, What are the Common mistakes a node js developer makes?
You should Know, What are the Common mistakes a node js developer makes?You should Know, What are the Common mistakes a node js developer makes?
You should Know, What are the Common mistakes a node js developer makes?
Surendra kumar
 

Similar to An Introduction to TypeScript (20)

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
 
Type script
Type scriptType script
Type script
 
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
 
Type script
Type scriptType script
Type script
 
Moving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should KnowMoving From JavaScript to TypeScript: Things Developers Should Know
Moving From JavaScript to TypeScript: Things Developers Should Know
 
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
 
Introjs10.5.17SD
Introjs10.5.17SDIntrojs10.5.17SD
Introjs10.5.17SD
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
Lecture-15.pptx
Lecture-15.pptxLecture-15.pptx
Lecture-15.pptx
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Reasons to Use Typescript for Your Next Project Over Javascript.pdf
Reasons to Use Typescript for Your Next Project Over Javascript.pdfReasons to Use Typescript for Your Next Project Over Javascript.pdf
Reasons to Use Typescript for Your Next Project Over Javascript.pdf
 
Csharp_Chap01
Csharp_Chap01Csharp_Chap01
Csharp_Chap01
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Migrating Web SDK from JS to TS
Migrating Web SDK from JS to TSMigrating Web SDK from JS to TS
Migrating Web SDK from JS to TS
 
CSC PPT 12.pptx
CSC PPT 12.pptxCSC PPT 12.pptx
CSC PPT 12.pptx
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
C# 6.0
C# 6.0C# 6.0
C# 6.0
 
Parse cloud code
Parse cloud codeParse cloud code
Parse cloud code
 
js.pptx
js.pptxjs.pptx
js.pptx
 
You should Know, What are the Common mistakes a node js developer makes?
You should Know, What are the Common mistakes a node js developer makes?You should Know, What are the Common mistakes a node js developer makes?
You should Know, What are the Common mistakes a node js developer makes?
 

Recently uploaded

All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
michniczscribd
 
How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
Zycus
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
kalichargn70th171
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
chandangoswami40933
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio, Inc.
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
jrodriguezq3110
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
confluent
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
Softradix Technologies
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
Alina Yurenko
 

Recently uploaded (20)

All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
 
How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdfSoftware Test Automation - A Comprehensive Guide on Automated Testing.pdf
Software Test Automation - A Comprehensive Guide on Automated Testing.pdf
 
Upturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in NashikUpturn India Technologies - Web development company in Nashik
Upturn India Technologies - Web development company in Nashik
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data PlatformAlluxio Webinar | 10x Faster Trino Queries on Your Data Platform
Alluxio Webinar | 10x Faster Trino Queries on Your Data Platform
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
Cost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App DevelopmentCost-Effective Strategies For iOS App Development
Cost-Effective Strategies For iOS App Development
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
 

An Introduction to TypeScript

  • 1. An Introduction to TypeScript The front-end React developer world is all abuzz with the fondness of using and preferring TypeScript over JavaScript. Although it’s not recommended for all types of projects it strongly overcomes many shortcomings of JavaScript and improves over it. In this beginner-friendly article, we will get to know what exactly TypeScript is, how is it a strongly-typed language, how it compares to JavaScript along with some of its highlighting features. Of course, we will be writing our first .ts code too!
  • 2. What is TypeScript? TypeScript is a strongly typed programming language that builds on JavaScript giving you better tooling at any scale. It’s a free and open-sourced project created by Microsoft. It is a ‘superset of JavaScript’, which means that you can continue to use the JavaScript skills you’ve already developed and add certain features that were previously unavailable to you. When compared to JavaScript, it’s a strongly typed language as opposed to JS which is a loosely typed language. You can consider this like JavaScript with superpowers! Now here’s where this language actually shines…remember the term ‘strongly typed’ we used above? What does it mean in this context? Well, this means that the data types of variables/functions and other primitives must be pre-defined. This is one of the most important features of TypeScript (that’s why it focuses so much on the ‘type’). Under the hood, it compiles to JavaScript, giving you the benefit of the JavaScript platform plus the intended advantages of types. Top features of TypeScript Now that you know a bit about this language, it’s time to see all the important and useful features it provides to the developer. Here are a few of them:
  • 3. 1. JavaScript and more: TypeScript adds additional syntactic sugar to your JavaScript code to support a tighter integration with your editor. 2. Runs anywhere where JavaScript does: TypeScript code converts to JavaScript which can then be run in a browser, on Node.js or Deno, and in your apps. 3. Safety with scalability: it uses type inference to give you great tooling without writing any additional code. 4. Editor support: most of the modern IDEs and code editors like VS Code come with built-in support for TypeScript files. You get autocompletion and auto- import support in VS Code out of the box. 5. Unique language features: here are some of the features which you will only find in a TypeScript code; Interfaces, Namespaces, Generics, Abstract classes, Data modifiers, and more! 6. Gradual adoption rate: you can apply the types to any previous JavaScript projects or codebase incrementally. With great editor support, TypeScript catches errors right inside your editor! 7. Easy to describe the data: it’s really easy to describe the shape of objects
  • 4. and functions in your code. This makes it possible to see documentation and issues in your editor. All of this should give you a general idea of what TypeScript is and what are its features, it’s time to write our first TypeScript code and see how to use it with JavaScript gradually. From JavaScript to TypeScript We won’t be diving straight into a TypeScript code. Instead, we want you to get familiar with an already existing knowledge of JavaScript and use it to convert a small JS code to TS code. Let’s say we have the following JavaScript code: // @ts-check function compact (arr) { if (orr. length > 10) return arr. trim(0, 10) return arr } Now you will see an error like “Cannot find name ‘orr‘.” Next, let’s say we do another mistake like using trim instead of slice on an array: function compact (arr: string[]) { if (arr.length > 10) return arr.slice(0, 10) return arr }
  • 5. We add a type of string[] (String array) for the arr parameter so it should always accept a string-based array and nothing else. Hence, we call TypeScript ‘strongly-typed’. Install and Setup TypeScript Time to write some TS code locally on our machine! You can install TypeScript globally via the following NPM command: npm install -g typescript Next, you can confirm the installation by running tsc –v to check the version of TypeScript installed in your system. Note that after you write a TypeScript code and want to run it, simply running tsc with file, the name won’t work as tsc is just a TypeScript compiler. We need Node.js to get the actual log output. We can do it by running this command for a “Hello World” program: tsc hello.ts && node hello.js Your first“Hello World!” in TypeScript After you installed TypeScript globally on your machine. You can open a suitable code editor like VS Code which has excellent support for the TypeScript tooling. 1. Create a new TypeScript file called helloWorld.ts. Then simply write a console log statement as you would do in JavaScript: console.log("Hello World!"); 2. Open your command prompt or Terminal window and run tsc helloWorld.ts. You will see nothing will happen as there are no types assigned here hence no type errors.
  • 6. 3. Instead you will see the TypeScript compiler generates a new helloWorld.js file in the same directory. This is the same TS code but it is the generated JS file output. 4. Time to make our console statement better. Let’s say we want to log the person’s name and date by asking the user to enter it through a greeter function: function greet(person, date) { console.log(`Hello ${person}, today is ${date}!`); } greet('Brendan'); Notice the way we are calling the greet function. If you run this you will get this error because we passed only 1 argument instead of the expected 2: // TS ERROR: Expected 2 arguments, but got 1. The parameters to the greet() function don’t have any explicitly defined types so TS will give it any type. 5. Let’s fix our function with the following valid code: // "greet() takes a person of type string, and a date of type Date" function greet(person: string, date: Date) { console.log(`Hello ${person}, today is ${date.toDateString()}`); } greet('Maddison', new Date()); Now we have explicitly defined all the data types and we can happily see the log statement printing the exact output we need. Just in case you are wondering the equivalent JS code of this will be:
  • 7. // "greet() takes a person of type string, and a date of type Date" function greet(person, date) { console.log("Hello " + person + ", today is " + date.toDateString() + "!"); } greet('Maddison', new Date()); With that, we have covered the bare-minimum basics you need to know of the TypeScript language. As you saw, it’s very much close to JavaScript so if you were already working with JavaScript then it should be easy to learn and migrate your projects to TypeScript. To make your work easy, we’ve created some dashboard templates. Check out now! Source: https://blog.wrappixel.com/introduction-to-typescript/ **********