TypeScript Introduction
What is TypeScript?
TypeScript is JavaScript with one big addition: types. A type tells what kind of value something should be, like a number, a piece of text, or true/false.
TypeScript help you catch mistakes early and make your code easier to understand.
TypeScript was made by Microsoft in 2012, to solve the challenges of developing large-scale, complex applications using JavaScript.
The following example shows a small TypeScript snippet - in TypeScript, you define what each value should be:
Example
let username: string = 'John';
let points: number = 32;
let active: boolean = true;
console.log(username, points, active);
Try it Yourself »
Example explained:
- username: string means username must be a string
- points: number means points must be a number
- active: boolean means active must be a boolean
So, TypeScript catches any mistake while you write the code, before anyone runs it!
TypeScript is not a new language you must learn. It is JavaScript with an extra layer of type checking!
Why use TypeScript?
JavaScript is a loosely typed language, and nothing stops you from mixing up values:
JS Example
function add(a, b) {
return a + b;
}
add(5, "10"); // "510"
(text joined, numbers are not added)
In TypeScript, you say what each value should be:
TypeScript Example
function add(a:
number, b: number): number {
return a + b;
}
add(5, "10"); //
Error: "10" is not a number
Advantages of using TypeScript:
- Find bugs early - Many mistakes show up as you type, not when users find them
- Better help in your editor - Your editor knows what each value is, so it can suggest names and show errors right away
- Code is easier to understand - Types act like notes that explain what a function expects and returns
- Safer changes - In big projects, TypeScript tells you everywhere that breaks when you change something
Any downsides?
- More to learn, and a bit more code to write
- An extra step is needed to turn TypeScript into JavaScript
- For very small scripts, plain JavaScript is often enough!
How do I use TypeScript?
Browsers do not understand TypeScript directly. You need a tool that turns your TypeScript into plain JavaScript.
A common way is to use the official TypeScript compiler, which transpiles TypeScript code into plain JavaScript.
The next section shows how to get the compiler setup for a local project.
Tip: Several code editors, such as Visual Studio Code, have built-in TypeScript support and can show errors as you write code!