TypeScript Tutorial
TypeScript is JavaScript with types. You write almost the same code, but you also say what kind of value each variable, parameter and object holds. TypeScript then checks your code and warns you about mistakes before you run it.
TypeScript was created by Microsoft. It is turned into normal JavaScript, so it runs anywhere JavaScript runs: in browsers, on Node.js servers and in mobile apps.
Why Learn TypeScript?
- It catches typing mistakes and wrong values while you write the code
- Your editor can suggest property names and show errors as you type
- Large projects stay easier to understand and change
- React, Angular, Next.js and Node.js projects use it more and more
- Many web development jobs now ask for it
A First Example
Example
function totalFee(monthly: number, months: number): number {
return monthly * months;
}
console.log(totalFee(3500, 4));
// totalFee("3500", 4); // Error: a string is not a number14000
The : number parts are type annotations. If someone passes a string by mistake, TypeScript shows an error straight away.
What You Will Learn
- How to install TypeScript and compile your first file
- Basic types, arrays and tuples
- Typing functions, objects, type aliases and interfaces
- Union types, literal types and narrowing
- Classes, access modifiers and generics
- A final quiz on the whole tutorial
This tutorial shows code with its output. To run the examples, install TypeScript on your computer as shown in the Get Started lesson, or use any online TypeScript playground.
Exercise
When does TypeScript find type errors in your code?
Before and After TypeScript
You should know JavaScript well before you start, because TypeScript builds on it. After this tutorial, use TypeScript in your own JavaScript projects, or review HTML and CSS for the front end.
Want to learn with a teacher? The Workownix Full Stack Web Development course covers JavaScript, TypeScript and modern frameworks with real projects, online or at our institute in Orangi Town, Karachi.
