# 快速入门
该章节针对初学者,讲解 TypeScript 环境搭建和核心概念。
# 环境搭建
在桌面执行如下代码 svn export .. 拷贝项目到本地。
然后阅读 运行项目,或者参照如下步骤自行搭建。
# 1. 全局安装 tsc 用于编译 TypeScript
npm i -g typeScript
# 2. 创建一个目录为 hello-world 的项目
mkdir hello-world
cd hello-world # 进入项目
# 3. 初始化 ts 配置文件
tsc --init
# 4. 初始化 package.json 配置文件
npm init -y
# 5. 创建初始项目文件
touch index.html index.ts
复制如下内容到对应文件。
index.ts
// 原始类型
let boolVal:boolean = true;
// 对象类型
interface Person {
name:string;
}
// 联合类型
type id = string | number;
// 交叉类型
type foo =
// * **原始类型(primitive types)** 类似 JavaScript 的基础类型,只是采用小写符号表示,例如 `boolean, number, string` 等
// * **对象类型(object types)** 类似 JavaScript 引用类型,包含 `class,interface,function,array` 等
// * **联合类型(unions types)** 类似不同类型求取并集,变量的值属于集合中任意类型均可
// * **交叉类型(intersection types)** 类似不同类型求取交集,,变量的值必须同时具备多个类型的特征
// * **类型参数(type parameters)** 限制类型的类型,例如泛型,后有详述
function greeter(person: string) {
return 'Hello, ' + person;
}
res = 1; // 触发类型推断
document.body.textContent = res;
index.html
<!DOCTYPE html>
<html>
<head>
<title>hello world</title>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
package.json
{
"scripts": {
"start": "tsc -w index.ts"
}
}
# 运行项目
在项目根目录运行 npm start,浏览器打开 index.html。
即可看到 hello world
tsc -w index.ts 表示实时编译 index.ts 文件,修改 index.ts hi 变量的值为 1, TypeScript 会抛出如下错误:
index.ts:1:7 - error TS2322: Type '1' is not assignable to type 'string'.
1 const hi: string = 1;
~~
该提示告知用户不能将 1 赋值给字符串类型,并显示了错误的行号。 这便是类型校验,变量只能被赋予限定的类型。
重新刷新 index.html 仍可看到浏览器输出 1。注意 TypeScript 不会阻止文件被编译为 js,即使类型检查出现错误。
# 类型注解
示例中我们采用 hi:string 的方式限制变量 hi 为字符串。
它是 TypeScript 用于注解变量类型的语法,术语为 类型注解(type annotation)
变量: 类型
你可以对函数等进行类型注解。修改 index.ts
// 标注函数的输入参数和返回值为 string 类型
function greeter(person: string): string {
return "Hello, " + person;
}
let user = 'tom';
document.body.textContent = greeter(user);
# 类型推断
除了采用 类型注解 显示标注类型。TypeScript 也可通过分析变量的初始化或代码逻辑来确定类型,这种隐式的类型检查机制称为 类型推断(Type Inference)
示例如下,修改 index.ts
function greeter(person: string) {
return 'Hello, ' + person;
}
let res = greeter('tom'); // 根据返回值推导 res 为 string 类型
res = 1; // 触发类型推断, res 不能赋值为数字
document.body.textContent = res;
# 类型系统
TypeScript 提供了丰富的类型系统来提供约束。 参考 TypeScript 类型规范 (opens new window) 整个类型系统分为如下几类:
- 任意类型(any type) 采用
:any标注,包含所有 JavaScript 的值,类型推断无法确定的值 TypeScript 都会认为是 any。 - 原始类型(primitive types) 类似 JavaScript 的基础类型,只是采用小写符号表示,例如
boolean, number, string等 - 对象类型(object types) 类似 JavaScript 引用类型,包含
class,interface,function,array等 - 联合类型(unions types) 类似不同类型求取并集,变量的值属于集合中任意类型均可
- 交叉类型(intersection types) 类似不同类型求取交集,,变量的值必须同时具备多个类型的特征
- 类型参数(type parameters) 限制类型的类型,例如泛型,后有详述
修改 index.ts
# 总结
本小节我们学习了如下知识
- 利用
npm i -g typescript安装tsc工具编译.ts后缀的文件-w选项开启实时编译
- 类型注解,通过
:类型的方式限制变量或函数类型 - 类型推断,在没有 类型注解 的时候 ,TypeScript 会根据变量的初始值自动推断类型
- 类型系统 包含
- 任意类型(any type)
- 原始类型(primitive types)
- 联合类型(unions types)
- 交叉类型(intersection types)
- 类型参数(type parameters)