Typescript:入门与实践

1. 什么是 TypeScript?

TypeScript 是 JavaScript 的一个超集,由微软开发并开源。扩展了 JavaScript 的语法,添加了静态类型检查和其他特性,使得代码更易于维护和调试。

1.1 TypeScript 的优势

  • 静态类型检查:在编译时捕获类型错误,减少运行时错误。
  • 更好的开发体验:提供代码补全、接口提示等功能,提升开发效率。
  • 兼容 JavaScript:TypeScript 是 JavaScript 的超集,可以直接运行 JavaScript 代码。
  • 渐进式学习:可以从 JavaScript 逐步迁移到 TypeScript,无需重写整个项目。

2. 安装 TypeScript

2.1 全局安装

通过 npm 全局安装 TypeScript:

1
npm install -g typescript

安装完成后,检查是否安装成功:

1
tsc -v  # 查看 TypeScript 版本

2.2 在项目中使用

在项目中安装 TypeScript:

1
npm install typescript --save-dev

初始化 TypeScript 配置文件:

1
npx tsc --init

这会生成一个 tsconfig.json 文件,用于配置 TypeScript 编译选项。


3. TypeScript 基础语法

3.1 类型注解

TypeScript 通过类型注解为变量、函数参数和返回值添加类型信息。

1
2
3
let message: string = 'Hello, TypeScript!';
let count: number = 42;
let isDone: boolean = false;

3.2 接口

接口用于定义对象的形状,确保对象具有特定的属性和方法。

1
2
3
4
5
6
7
8
9
interface User {
name: string;
age: number;
}

const user: User = {
name: 'Wang',
age: 25
};

3.3 类

TypeScript 支持面向对象编程,可以使用类、继承、修饰符等特性。

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
class Animal {
name: string;

constructor(name: string) {
this.name = name;
}

speak(): void {
console.log(`${this.name} speak 喵喵`);
}
}

class Dog extends Animal {
color: string;

constructor(name: string, color: string) {
super(name);
this.color = color;
}

speak(): void {
console.log(`${this.name} speak 旺旺`);
}
}

const dog = new Dog('Bob', 'Beta');
dog.speak(); // 输出: Bob speak旺旺.

3.4 泛型

泛型用于创建可重用的组件,支持多种类型。

1
2
3
4
5
6
function identity<T>(arg: T): T {
return arg;
}

const output1 = identity<string>('Hello');
const output2 = identity<number>(42);

3.5 枚举

枚举用于定义一组命名的常量。

1
2
3
4
5
6
7
8
enum Color {
Red,
Green,
Blue
}

const color: Color = Color.Green;
console.log(color); // 输出: 1

4. TypeScript 高级特性

4.1 类型别名

类型别名用于为复杂类型定义一个新的名称。

1
2
3
4
5
6
7
8
type StringOrNumber = string | number;

function printValue(value: StringOrNumber): void {
console.log(value);
}

printValue('Hello'); // 输出: Hello
printValue(42); // 输出: 42

4.2 联合类型和交叉类型

  • 联合类型:表示一个值可以是多种类型之一。
  • 交叉类型:表示一个值必须同时满足多种类型。
1
2
3
4
5
6
7
8
type A = { a: string };
type B = { b: number };

type C = A & B; // 交叉类型
type D = A | B; // 联合类型

const obj1: C = { a: 'Hello', b: 42 };
const obj2: D = { a: 'Hello' };

4.3 类型断言

类型断言用于告诉编译器某个值的类型。

1
2
const value: any = 'Hello, TypeScript!';
const length: number = (value as string).length;

5. TypeScript 实践

5.1 与 React 结合

在 React 项目中使用 TypeScript,可以为组件、状态和属性添加类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import React, { useState } from 'react';

interface Props {
name: string;
}

const Greeting: React.FC<Props> = ({ name }) => {
const [count, setCount] = useState<number>(0);

return (
<div>
<h1>Hello, {name}!</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};

export default Greeting;

5.2 与 Node.js 结合

在 Node.js 项目中使用 TypeScript,可以为模块、函数和对象添加类型。

1
2
3
4
5
6
7
8
9
10
11
import express, { Request, Response } from 'express';

const app = express();

app.get('/', (req: Request, res: Response) => {
res.send('Hello, TypeScript with Node.js!');
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});