TypeScript is a typed superset of “JavaScript“, but it assumes you know what a “superset” is and what “typed” means. So instead, to keep things simple, you can think of TypeScript as “a layer on top” of JavaScript.
TypeScript is a layer because you can write TypeScript code in your editor. After a compilation, all that TypeScript stuff is gone, and you’re left with plain, simple JavaScript.
If the idea of the compilation step confuses you, remember that JavaScript is already compiled and interpreted. There is a JavaScript engine that reads and executes your code.
JavaScript engines cannot read TypeScript code, so any TypeScript file should go under the “pre-translation” process, called compilation.
After the first compilation step, you’re left with pure JavaScript code, ready to run in the browser. You’ll see later how the TypeScript compilation is done.
What are the types in TypeScript?
By now, you should’ve got a hint of what TypeScript does. Everything revolves around types. These are not the classic JavaScript “types” like String, Object, Boolean, etc.
TypeScript adds more type on its own like any (and more).
“any” in particular is a “loose” TypeScript type.
It means: this variable might be of any type: string, boolean, object, I don’t care, which is like having no type checking at all. With strict set to true instead, you say to TypeScript, “don’t allow ambiguity in my code”.
For this reason, I recommend keeping the maximum strictness on TypeScript, even if it can be harder to fix all errors at first. And now we’re almost ready to see TypeScript in action!
Typescript example
TypeScript is an open-source, object-oriented language maintained by Microsoft. Due to the static typing in TS, code written in TypeScript is more predictable and is generally easier to debug than normal JS.
Before coding in TypeScript, we need to install it on our local machine. We can pull the typescript package using NPM, and it is better to install it globally by entering the following command.
npm install -g typescript
When it is installed, we can verify it by running the command.
tsc -v
It will display the version of the typescript recently installed on your machine.
TypeScript coding
Let us write some code in typescript and see the output. The file extension for TypeScript is .ts.
Create one file called app.ts and add the following code.
const spiderman = (person) => {
return 'Hello, ' + person;
}
let user = 'Peter Parker';
console.log(spiderman(user));
First, we need to compile this code to Javascript, and then we can use that file in either server or the browser. We will test our code on the server because we use Node.js.
Now compile the file using the following command. It will generate the same-named javascript file.
tsc app.ts
So, in the project root, you can see that one more file has been created called app.js.
let spiderman = function (person) {
return 'Hello, ' + person;
};
let user = 'Peter Parker';
console.log(spiderman(user));
Now, run that file as a node server using the following command.
node app
It will return the output like below.
Text Editors With TypeScript Support
TypeScript is an open-source project, but it was developed and maintained by Microsoft Inc. and was initially supported only in Microsoft’s Visual Studio platform.
Nowadays, many text editors and IDEs, natively or through plugins, support the TypeScript syntax, auto-complete suggestions, error catching, and even built-in compilers.
- Visual Studio Code – Microsoft’s other lightweight open-source code editor. TypeScript support is built-in.
- Official Free Plugin for Sublime Text.
- The latest version of WebStorm comes with built-in support.
- More including Vim, Atom, Emacs, and others.
Static Typing
Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable.
const spiderman = (person: String) => { return 'Hello, ' + person; } let user = 1; console.log(spiderman(user));
In the above example, we have told the TS compiler that the spiderman function expects an argument as a string, not an integer, object, or array datatype. Still, we have passed an integer argument.
Now see the below output.
We have got an error saying that the number is not assignable to the parameter String.
A compelling feature of TypeScript is the support of static typing.
It means that you can declare the types of variables, and the compiler will ensure that they are not assigned the wrong values.
Datatypes in TypeScript
- Number – A number type represents all the numeric values; there aren’t separate definitions for integers, floats, or others.
- String – The text type datatype, like in vanilla JS strings, can be surrounded by ‘single quotes’ or “double quotes.”
- Boolean is true or false; 0 and 1 will cause the compilation error.
- Any – A variable with this type can have its value set to the string, number, or anything else.
- Arrays – Has two possible syntaxes: my_arr: number[] or my_arr: Array<number>.
- Void – Used on the function that doesn’t return anything.
Object-oriented programming in TypeScript
TypeScript supports all the latest features of ES Next and object-oriented programs, such as classes and interfaces.
This capability is a huge boost to JavaScript since it has always struggled with its OOP functionality, especially since developers started using it for large-scale applications.
Interfaces in TypeScript
Interfaces are used to type-check whether the object has a specific structure.
We can name the particular combination of variables by defining an interface, ensuring they will always go together.
When compiled from Typescript to JavaScript, interfaces disappear – their only purpose is to help in the development stage.
interface OS {
name: String;
language: String;
}
const desert = (type: OS): void => {
console.log('Android ' + type.name + ' has ' + type.language + ' language');
};
const nougat = {
name: 'N',
language: 'Java'
}
desert(nougat);
In the above example, we have created one interface called OS. It has two properties called name and language.
The next step is to define a function with one argument called type, which is the type of interface OS.
You can compile that file to the JS and see the output.
tsc app.ts
Your app.js file looks like the below code.
var desert = function (type) {
console.log('Android ' + type.name + ' has ' + type.language + ' language');
};
var nougat = {
name: 'N',
language: 'Java'
};
desert(nougat);
The output is the following.
Class in TypeScript
In an object-oriented programming language, the class is the template of objects. Thus, the class defines how an object would look regarding that object’s functionalities.
The class also encapsulates the data for an object.
TypeScript has built-in support for classes unsupported by ES5 and earlier versions of Javascript, which means that we can use the class keyword to declare one easily.
Let’s see the following example.
class Car {
model: String;
doors: Number;
isElectric: Boolean;
constructor(model: String, doors: Number, isElectric: Boolean) {
this.model = model;
this.doors = doors;
this.isElectric = isElectric;
}
make(): void {
console.log(`This car is ${this.model} which has ${this.doors} doors` );
}
}
let newCar = new Car('Innova', 4, false);
newCar.make();
In the above example, we defined one class with a parameterized constructor, properties, and methods.
Then, we created an object of that class and passed the parameter to construct an object and assign the values.
Then, we called the make method to create and show the car in the console. Finally, compile the file and see the output inside the console.
tsc app.ts
If the code is errorless, you will see the updated app.js file and now run that file.
node app
See the output below.
That’s it for the Typescript example.
Krunal,
The line :-
console.log(‘This car is ${this.model} which has ${this.doors} doors’);
only prints :-
This car is ${this.model} which has ${this.doors} doors
I had to remove the “$” sign and the curly braces and change it to this :-
console.log(‘This car is ‘ + this.model + ‘ which has ‘ + this.doors + ‘ doors’);
before it was able to print :-
This car is Innova which has 4 doors
that was because you use ” instead of “this is a string template that is in ES6 so if you used ‘ ‘ you needed to delete the {} and $, and add the +.
you have to use bacticks(“) and then use $ in it
@Foon Lam Says
You are using single-qoutes, that’s why it’s not working.
Use have to use ‘backticks’ instead.
https://stackoverflow.com/questions/27678052/usage-of-the-backtick-character-in-javascript