This tutorial aims to provide an introduction to TypeScript, a popular statically typed superset of JavaScript that adds optional types to JavaScript. By the end of this tutorial, you should be able to set up a TypeScript development environment, write a simple TypeScript program, and understand the TypeScript compilation process.
sh
npm install -g typescript
hello.ts
and add the following code:ts
let message: string = 'Hello, TypeScript!';
console.log(message);
let
keyword declares a variable in TypeScript. The : string
annotation adds a type annotation to the variable. This is a specific feature of TypeScript - JavaScript does not have type annotations.sh
tsc hello.ts
hello.ts
to JavaScript code in hello.js
.Here's an example of a TypeScript variable with a type annotation:
let message: string = 'Hello, TypeScript!';
In this line of code, we declare a variable message
with a type annotation string
. TypeScript will now ensure that message
always holds a string.
Here's an example of a TypeScript array:
let names: string[] = ['Jake', 'Amy', 'Holt'];
In this line of code, we declare a variable names
with a type annotation string[]
. The string[]
type annotation ensures that names
always holds an array of strings.
In this tutorial, we covered how to set up a TypeScript development environment, how to write a simple TypeScript program, and how to compile TypeScript code to JavaScript.
You can continue learning more about TypeScript by understanding more about types, functions, interfaces, and classes in TypeScript.
function reverseString(s: string): string {
return s.split('').reverse().join('');
}
console.log(reverseString('TypeScript')); // Output: 'tpircSepyT'
function sumArray(numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sumArray([1, 2, 3, 4, 5])); // Output: 15
Try to solve problems from coding platforms like LeetCode and HackerRank using TypeScript. This will not only improve your TypeScript skills but also your problem-solving skills.