TypeScript 入门教程:从零基础到精通的完整指南
前言
TypeScript 是 JavaScript 的超集,它增加了静态类型检查和其他高级功能,目的是使代码更加健壮和可维护。它是由微软开发和维护的,最初发布于 2012 年,并得到了广泛的应用。TypeScript 在编译时会将代码转换为标准的 JavaScript,因此可以在任何支持 JavaScript 的环境中运行。
TypeScript 与java对比
| 特点 | TypeScript | Java |
|---|---|---|
| 编译与运行 | 编译为 JavaScript,运行于浏览器或 Node.js | 编译为字节码,运行于 JVM |
| 类型系统 | 静态类型检查,可选类型 | 强类型,必须显式声明类型 |
| 运行环境 | 前端、Node.js | 服务器端、企业级系统、安卓开发 |
| 面向对象支持 | 支持 OOP,类和接口为增强型 JavaScript | 纯粹的 OOP 语言 |
| 模块化 | 支持 ES 模块(import/export) | Java 9 之后支持模块系统 |
| 调试工具 | 通过 Source Maps 调试 TypeScript 代码 | 直接调试字节码,IDE 支持完善 |
| 主要应用场景 | 前端开发,Node.js 后端开发 | 企业级应用、安卓开发、分布式系统 |
typescript与java语法对比
以下是 TypeScript 和 Java 在语法方面的对比表格:
| 功能 | TypeScript | Java |
|---|---|---|
| 变量声明 | let, const, var |
int, double, String, boolean, char, final |
| 类型声明 | number, string, boolean, void, any, unknown, enum, tuple, object |
int, double, String, boolean, char, Object, List, Map, Set |
| 常量 | const PI: number = 3.14; |
static final double PI = 3.14; |
| 函数声明 | function add(x: number, y: number): number { return x + y; } |
int add(int x, int y) { return x + y; } |
| 箭头函数 | const multiply = (x: number, y: number): number => x * y; |
不支持箭头函数 |
| 类定义 | class Person { name: string; constructor(name: string) { this.name = name; } } |
class Person { String name; Person(String name) { this.name = name; } } |
| 接口 | interface Animal { name: string; } |
interface Animal { String getName(); } |
| 继承 | class Dog extends Animal { breed: string; } |
class Dog extends Animal { String breed; } |
| 多态 | class Animal { speak() { console.log("Animal sound"); } } class Dog extends Animal { speak() { console.log("Bark"); } } |
class Animal { void speak() { System.out.println("Animal sound"); } } class Dog extends Animal { void speak() { System.out.println("Bark"); } } |
| 枚举 | enum Direction { Up, Down, Left, Right } |
public enum Direction { UP, DOWN, LEFT, RIGHT } |
| 泛型 | function identity<T>(arg: T): T { return arg; } |
public <T> T identity(T arg) { return arg; } |
| 模块 | export class Person {} import { Person } from './person'; |
package com.example; import com.example.Person; |
| 异常处理 | try { /* code */ } catch (error) { /* handle error */ } |
try { /* code */ } catch (Exception e) { /* handle error */ } |
| 接口实现 | class Dog implements Animal { name: string; constructor(name: string) { this.name = name; } } |
class Dog implements Animal { String name; } |
| 数据结构 | let arr: number[] = [1, 2, 3]; let map: Map<string, number> = new Map(); |
int[] arr = {1, 2, 3}; Map<String, Integer> map = new HashMap<>(); |
| 类型推断 | TypeScript 自动推断类型 | Java 强制要求显式声明类型 |
| 可选参数 | function greet(name: string, age?: number) { /* code */ } |
void greet(String name, Integer age) { /* code */ } |
| 默认参数 | function greet(name: string, age: number = 30) { /* code */ } |
void greet(String name, Integer age) { if (age == null) age = 30; /* code */ } |
| 构造函数 | constructor(public name: string) {} |
Person(String name) { this.name = name; } |
| 属性访问修饰符 | public, private, protected |
public, private, protected |
| 异步操作 | async function fetchData() { let response = await fetch(url); } |
public Future<Data> fetchData() { return CompletableFuture.supplyAsync(() -> { /* code */ }); } |
1 环境安装
1.1 npm安装
npm install -g typescript
查看版本
tsc --version
1.2 pycharm配置
安装
npm install typescript ts-node --save-dev
项目通用配置:tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"strict": true,
"esModuleInterop": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
原创:有勇气的牛排
https://www.couragesteak.com/article/477
2 初始案例
hello.ts
let msg: string = "有勇气的牛排"
console.log(msg)
编译
tsc hello.ts
运行
node hello.js
3 数据类型
3.1 布尔 boolean
boolean 类型只允许 true 或 false 两个值。
let is_ban = true;
console.log(is_ban)
3.2 数值 number
number 类型用于表示所有的数字,包括整数和浮点数。
let age: number = 18;
let hex: number = 0xf00d; //16进制
let binary: number = 0b1010; //2进制
let octal: number = 0o744; // 8进制
console.log(age);
console.log(hex);
console.log(binary);
console.log(octal);
3.3 字符串 string
let nickname: string = "有勇气的牛排"
let introduce: string = `${nickname}是编程大佬`
console.log(nickname);
console.log(introduce);
3.4 数组 array
tuple 允许表示一个已知数量和类型的数组,各元素的类型可以不同。
let id_list: number[] = [1, 2, 3] // 数字数组
let name_list: Array<string> = ['A', 'B', 'C'] // 字符串数组(泛型写法)
console.log(id_list);
console.log(name_list);

3.5 元組 tuple
let tuple: [string, number]
tuple = ["你好", 13579]
console.log(tuple);
3.6 枚举 enum
enum Color {
Red,
Green,
Blue
}
let color: Color = Color.Blue;
console.log(color);
指定开始索引
enum Direction {
Up = 1,
Down,
Left,
Right
}
console.log(Direction.Left);
3.7 任意类型 any
any 类型允许我们对某个值不确定其具体类型时使用,跳过类型检查。
let data: any = 1;
console.log(data);
data = "有勇气的牛排"
console.log(data);
data = true
console.log(data);

3.8 空类型 void
void 一般用于表示没有返回值的函数。它表示没有任何类型,常用于函数返回值。
function notifyMsg(): void {
console.log("有勇气的牛排");
}

3.9 null和underfined
TypeScript 中 null 和 undefined 是所有类型的子类型。
-
null表示空值, -
undefined表示未定义的值。
let id: undefined = undefined;
let name: null = null;
3.10 对象 object
object 类型表示非原始类型的对象,例如数组、函数等。
let person: object = {
id: 1,
name: "有勇气的牛排"
}
console.log(person)

3.11 永不存在的值类型 never
function error(msg: string): never {
throw new Error(msg);
}
error("这是一个异常");

3.12 联合类型 union types
let value: string | number;
value = "有勇气的牛排"
console.log(value);
value = 1;
console.log(value);

3.13 類型別名 type
type 關鍵字可以為聯合類型或複雜類型創建別名,簡化代碼
type ID = number | string;
let userId: ID;
userId = 101;
userId = "有勇气的牛排";
console.log(userId);

3.14 类型断言 type assertions
类型断言,允许开发者说动指定某个值的类型,类似于类型转换。
let someValue: any = "有勇气的牛排";
let strLength: number = (someValue as string).length;
console.log(strLength);

3.15 unknow
unknow 是typescript中比any更安全的类型。在不知道类型的时候可以使用。
在使用之前需要进行类型检查。
let value:unknown="有勇气的牛排Hello";
if(typeof value==='string'){
console.log(value.toUpperCase())
}

4 特殊數據類型
4.1 接口 interface
4.1.1 常规使用
interface 用於定義對象結構,描述对象包含哪些属性、属性的类型等。
interface Person {
id: number,
name: string,
}
let cs: Person = {
id: 1,
name: "有勇气的牛排"
}
console.log(cs.name)

4.1.2 接口readonly
readonly 修饰符用于定义只读属性,防止在初始化后修改该属性。
interface People {
readonly id: number;
name: string;
}
let cs: People = {
id: 2,
name: "测试"
}
// 尝试修改只读属性
cs.id = 3; // 这里应该会报错,因为 id 是只读属性
console.log(cs);
4.1.3 接口可选属性 optional properties
在接口中定义可选属性,可以使用 ? 标记某个属性
interface People {
id: number;
name: string;
role?: string;// 可选属性
}
let cs: People = {
id: 1,
name: "有勇气的牛排",
// role可以不赋值
}

4.2 函数 function
function add(a: number, b: number): number {
return a+b;
}
console.log(add(1,2));
4.3 类
class Person {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
introduce() {
console.log(`${this.name}的id为:${this.id}`)
}
}
// 使用类作为类型
let cs: Person = new Person(1, "有勇气的牛排");
cs.introduce();

4.4 类实现接口
interface PersonInterface {
id: number;
name: string;
introduce(): void;
}
// 接口扩展类的结构。也可以在接口中定义类的行为,或者让一个类实现接口。
class Person implements PersonInterface{
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
introduce() {
console.log(`${this.name}的id为:${this.id}`)
}
}
// 使用类作为类型
let cs: Person = new Person(1, "有勇气的牛排");
cs.introduce();
4.5 泛型
4.5.1 泛型函数
function identity<T>(arg: T): T {
return arg;
}
let res1 = identity<string>("有勇气的牛排");
let res2 = identity<number>(100);
console.log(res1);
console.log(res2);
5 模块化开发
获取日期案例
util_time.ts
// DateUtils.ts
export class UtilTime {
// 获取当前日期
getCurrentDate(): string {
const today = new Date();
const year = today.getFullYear();
const month = (today.getMonth() + 1).toString().padStart(2, "0");
const day = today.getDate().toString().padStart(2, "0");
const hours = today.getHours().toString().padStart(2, "0");
const minutes = today.getMinutes().toString().padStart(2, "0");
const seconds = today.getSeconds().toString().padStart(2, "0");
return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
}
// 获取 n 天前的日期
getDateYesterday(days: number): string {
const date = new Date();
date.setDate(date.getDate() + days); // 设置为 n 天前
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, "0");
return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
}
}
main.ts
// main.ts
import { UtilTime } from './util_time';
const util_time = new UtilTime();
// 获取当前日期
const currentDate = util_time.getCurrentDate();
console.log("当前日期:", currentDate);
// 获取昨天日期
const daysBefore = -1;
const dateBefore = util_time.getDateYesterday(daysBefore);
console.log(`昨天日期:`, dateBefore);

标签: