TypeScript是什么
# TypeScript 是什么

# 体验 typescript
因为 node.js 和浏览器只认 js,不认识 ts 代码。需要先将 TS 代码转化为 JS 代码,然后才能运行
- 全局安装 typescript
npm i -g typescript
1
- 验证是否安装成功
tsc –v # 成功安装后会显示Typescript版本如Version 5.8.3
1
编译并运行 typescript
使用 tsc 命令编译 ts 文件
tsc index.ts
1自动化编译
- 创建 TypeScript 编译控制⽂件
tsc --init
1- 监视⽬录中的 .ts ⽂件变化
tsc --watch 或 tsc -w
1- 当编译出错时不⽣成 .js ⽂件
tsc --noEmitOnError --wat
1
# 基础类型
# 常用基础类型
TS 中的常用基础类型细分为两类:1 JS 已有类型 2 TS 新增类型
JS 已有类型
原始类型:number/string/boolean/null/undefined/symbol
对象类型:object(包括,数组、对象、函数等对象)
TS 新增类型
- 联合类型、自定义类型(类型别名)、接口、元组、字面量类型、枚举、void、any 等
# 类型注解
// 基础类型
let age: number = 20;
let name: string = "张三";
let b: boolean = true;
let n: null = null;
let u: undefined = undefined;
let s: symbol = Symbol();
// 数组类型(两种写法)
let arr: number[] = [1, 2, 3];
let str: string[] = ["1", "2", "3"];
/**
* 表示这个数组中既有string类型,也有number类型
* | 在 TS 中叫做联合类型(由两个或多个其他类型组成的类型,表示可以是这些类型中的任意一种)
*/
let arr_str: (string | number)[] = [1, 34, 4, "8"];
let arr1: Array<string> = ["1", "3"];
let arr3: Array<number | string> = [1, "3"];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 类型别名
类型别名
类型别名(自定义类型):为任意类型起别名。
使用场景:当同一类型(复杂)被多次使用时,可以通过类型别名,简化该类型的使用。
type customArr = (string | number)[];
let arr3: customArr = [1, 3, "4"];
1
2
2
1
上次更新: 2025/06/17, 23:00:40