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.
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/
**********