TypeScript Tutorial

1. Installing TypeScript and Demo

Enter the command line and following command:

1
2
npm install -g typescript
tsc -V

Compile the ts file:

1
tsc xxx.ts

ts demo

1
console.log('Hello TS')
1
tsc hello.ts 

2. Type Declaration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Declare variables and specify types
let a: number;
a = 10;
a = 33;
// a = 'hello'; // error TS2322: Type 'string' is not assignable to type 'number'.

let b: string;
b = 'hello';
// b = 123; // error TS2322: Type 'number' is not assignable to type 'string'.

// Declare variables and assign values
let c: boolean = true;

// If a variable is declared and assigned, TS can automatically detect the type of the variable
let d = true;
// c = 123; // error TS2322: Type 'number' is not assignable to type 'boolean'.

// JavaScript does not consider the type and number of parameters
// function sum(a , b){
// return a + b;
// }
//
// sum(123, 456); // 579
// sum(123, "456"); // 123456

// a is number, b is number, return val is number
function sum(a: number, b: number): number {
return a + b;
}

sum(123, 456);
// sum(123, "456"); // error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
// sum(123, 456, 789); // error TS2554: Expected 2 arguments, but got 3.

TypeScript Tutorial
https://www.hardyhu.cn/2023/02/17/TypeScript-Tutorial/
Author
John Doe
Posted on
February 17, 2023
Licensed under