Discovering TypeScript
TypeScript is not a new programming language, but rather a typed superset of JavaScript that transpiles to plain JavaScript. In other words, a valid JavaScript code is also a valid TypeScript code. Developed and maintained by Microsoft since 2012, it is designed to solve the shortcomings of JavaScript when developing large-scale applications.
Why should you write in TypeScript?
It increases readability and maintainability
Typings are practically the best documentation you can have. You know how to use most of the functions by just looking at their type definition.
TypeScript will tell you about any errors it finds during compilation, for example, spelling mistakes and undeclared variables. It’s always better to notice errors during compilation, rather than during runtime. The full list of TypeScript compiler errors can be found on TypeScript GitHub Repository.
This script also enhances the functionalities provided by code editors and IDE (Integrated Development Environment), such as auto-completion, definition prompting, jump-to-definition, and refactoring.
It is very flexible
It is very forgiving because even though its transpiler detects errors in your .ts files, it will still transpile them into .js files. Having said that, you can disable this feature by modifying the “tsconfig.json” file in your project folder.
In addition, TypeScript is also very flexible. As mentioned before, it is a superset of JavaScript. As a result, you can directly rename your .js` files as .ts files. Types are optional. You can explicitly tell TypeScript the types of variables you are working with or let it infer types by itself.
TypeScript compiler also allows you to transpile your .ts files into .js files in different ECMAScript target versions, from “ES3” to “ESNext”, providing the maximum amount of possible backward compatibility.
It has an active community
Most of third-party JavaScript libraries provide typing definition files (.d.ts) written in TypeScript, so that you can make use of the auto-completion feature provided by code editors and IDEs. There are different frameworks that use TypeScript in their projects, such as Angular, NativeScript, Ionic.
TypeScript also embraces ES6 standards and provides some support for ES7 drafting standards.
What are the disadvantages of TypeScript?
Everything has two sides. For example, code written in TypeScript can seem to be too cumbersome since type annotations need to be used everywhere in order to get the most out of TypeScript.
TypeScript cannot be run on browsers directly and it needs to be transpiled into JavaScript first. Therefore, any modifications in your code written in this script can lead to another transpilation. However, you can set the compiler to watch your .ts files so that it can automatically transpile your .ts files into .js files.
How to use TypeScript?
To use this script, you first need Node.js to be installed on your computer.
Then, open your command line tool and type the following command to install it.
npm install -g typescript
Once it finished, you can run the following command to transpile your `.ts` files. In this example, we’re going to transpile our `hello_world.ts` file.
tsc hello_world.ts
Example
We’re going to write some TypeScript code to discover the power of TypeScript.
Let’s say we have the following data:
let lloyd = { name: 'Lloyd', homework: [90.0, 97.0, 75.0, 92.0], quizzes: [88.0, 40.0, 94.0], tests: [75.0, 90.0] }; let alice = { name: 'Alice', homework: [100.0, 92.0, 98.0, 100.0], quizzes: [82.0, 83.0, 91.0], tests: [89.0, 97.0] }; let tyler = { name: 'Tyler', homework: [0.0, 87.0, 75.0, 22.0], quizzes: [0.0, 75.0, 78.0], tests: [100.0, 100.0] }; let students = [lloyd, alice, tyler];
We can write an interface to assure the data structure. We know that a student should have a name of type string, 3 arrays of scores (type number) for homework, quizzes and tests respectively. The possible interface can resemble the following:
interface Student { name: string; homework: number[]; quizzes: number[]; tests: number[]; }
Once we created the interface “Student”, we can assign the student objects with this type.
interface Student { name: string; homework: number[]; quizzes: number[]; tests: number[]; } let lloyd: Student = { name: 'Lloyd', homework: [90.0, 97.0, 75.0, 92.0], quizzes: [88.0, 40.0, 94.0], tests: [75.0, 90.0] }; let alice: Student = { name: 'Alice', homework: [100.0, 92.0, 98.0, 100.0], quizzes: [82.0, 83.0, 91.0], tests: [89.0, 97.0] }; let tyler: Student = { name: 'Tyler', homework: [0.0, 87.0, 75.0, 22.0], quizzes: [0.0, 75.0, 78.0], tests: [100.0, 100.0] }; let students: Student[] = [lloyd, alice, tyler];
Let’s say we create a new object called “mary” like this:
let mary: Student = { name: 'Mary' };
If you run the TypeScript compiler, an error message will appear.
[ts] Type '{ name: string; }' is not assignable to type 'StudentResults'. Property 'homework' is missing in type '{ name: string; }'.
The reason for this is that “mary” is of type “Student”, and we defined that a “Student” should have a name of type “string”, homework, quizzes, tests of type “number array”. However, in our “mary” object, it only has a name, which resulted in an error.
Now, we can start writing the functions. First, let’s write a function to calculate the average score of a number array.
function average(scores) { return scores.reduce((accumulator, currentValue) => accumulator + currentValue, 0) / score.length; }
In this case, however, the code block isn’t type-safe because we can pass in anything to the “scores” parameter, which will cause the function to break. We can add types to ensure that only a number array is passed in as the “scores” parameter and the function should return a number as follows:
function average(scores: number[]): number { return scores.reduce((accumulator, currentValue) => accumulator + currentValue, 0) / score.length; }
If we try to pass in “lloyd.name” as the “scores” parameter, it will result in an error again.
[ts] Argument of type 'string' is not assignable to parameter of type 'number[]'.
The complete code is available on my GitLab Repository.
Further Reading
Official TypeScript Documentation
DefintitelyTyped
Article written by Siu Kei CHEUNG, CAWEB Master’s
Other articles
-
Chrome Music Lab : l’application de Google qui lie web et musique
-
How and Why Google Plans to Fight Against AI Generated Content
-
The importance of a good translation and localization for the pharmaceutical industry
-
Taking your international marketing campaign to local markets: interview with transcreation specialist Claudia Benetello