Skip to content

TypeScript 特性

TypeScript 是 JavaScript 的超集,它添加了许多强大的特性,使代码更加可靠、可维护和易于理解。以下是 TypeScript 的主要特性:

1. 静态类型检查

TypeScript 最核心的特性是静态类型检查,它可以在编译时发现类型错误,减少运行时错误。

typescript
// TypeScript 代码
function add(a: number, b: number): number {
  return a + b;
}

// 正确的调用
add(1, 2); // 返回 3

// 错误的调用(编译时会报错)
add("1", "2"); // 类型错误:不能将字符串赋值给类型 number

2. 类型推断

TypeScript 具有强大的类型推断能力,即使你不明确指定类型,它也能根据上下文推断出正确的类型。

typescript
// TypeScript 会推断出 message 是 string 类型
let message = "Hello TypeScript";

// TypeScript 会推断出 numbers 是 number[] 类型
let numbers = [1, 2, 3, 4, 5];

// TypeScript 会推断出 person 是 { name: string; age: number } 类型
let person = { name: "John", age: 30 };

3. 接口

接口是 TypeScript 的一个重要特性,它定义了对象的结构和类型。

typescript
interface Person {
  name: string;
  age: number;
  email?: string; // 可选属性
}

function greet(person: Person): string {
  return `Hello, ${person.name}!`;
}

const john: Person = { name: "John", age: 30 };
greet(john); // 正确

const jane: Person = { name: "Jane", age: 25, email: "jane@example.com" }; // 正确

const tom: Person = { name: "Tom" }; // 错误:缺少 age 属性

4. 类

TypeScript 支持面向对象编程,包括类、继承、多态等特性。

typescript
class Animal {
  protected name: string;

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

  makeSound(): void {
    console.log("Some generic sound");
  }
}

class Dog extends Animal {
  constructor(name: string) {
    super(name);
  }

  makeSound(): void {
    console.log("Woof! Woof!");
  }
}

const dog = new Dog("Buddy");
dog.makeSound(); // 输出 "Woof! Woof!"

5. 泛型

泛型允许你编写可重用的代码,适用于多种类型。

typescript
function identity<T>(value: T): T {
  return value;
}

// 使用泛型函数
const number = identity<number>(42); // number 类型
const string = identity<string>("Hello"); // string 类型

// 泛型类
class Box<T> {
  private value: T;

  constructor(value: T) {
    this.value = value;
  }

  getValue(): T {
    return this.value;
  }
}

const numberBox = new Box<number>(42);
const stringBox = new Box<string>("Hello");

6. 模块

TypeScript 支持 ES 模块系统,可以将代码分割成多个文件,提高代码的可维护性。

typescript
// math.ts
export function add(a: number, b: number): number {
  return a + b;
}

export function subtract(a: number, b: number): number {
  return a - b;
}

// app.ts
import { add, subtract } from "./math";

console.log(add(1, 2)); // 3
console.log(subtract(5, 3)); // 2

7. 命名空间

命名空间可以用来组织代码,避免命名冲突。

typescript
namespace MathUtils {
  export function add(a: number, b: number): number {
    return a + b;
  }

  export function subtract(a: number, b: number): number {
    return a - b;
  }
}

MathUtils.add(1, 2); // 3
MathUtils.subtract(5, 3); // 2

8. 类型别名

类型别名允许你为复杂的类型定义一个简短的名称。

typescript
type UserId = number;
type UserName = string;
type User = {
  id: UserId;
  name: UserName;
  email: string;
};

const user: User = {
  id: 1,
  name: "John",
  email: "john@example.com"
};

9. 联合类型和交叉类型

联合类型允许一个变量可以是多种类型之一,交叉类型允许将多个类型合并为一个类型。

typescript
// 联合类型
let value: string | number;
value = "Hello";
value = 42;

// 交叉类型
interface Person {
  name: string;
}

interface Employee {
  employeeId: number;
}

type EmployeePerson = Person & Employee;

const emp: EmployeePerson = {
  name: "John",
  employeeId: 123
};

10. 字面量类型

字面量类型允许你指定变量只能是特定的值。

typescript
type Direction = "up" | "down" | "left" | "right";

function move(direction: Direction): void {
  console.log(`Moving ${direction}`);
}

move("up"); // 正确
move("down"); // 正确
move("left"); // 正确
move("right"); // 正确
move("forward"); // 错误:类型 "forward" 不能赋值给类型 Direction

11. 枚举

枚举允许你定义一组命名的常量。

typescript
enum Color {
  Red,
  Green,
  Blue
}

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

// 字符串枚举
enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}

const direction: Direction = Direction.Up;
console.log(direction); // 输出 "UP"

12. 高级类型

TypeScript 提供了许多高级类型,如 PartialRequiredReadonlyRecord 等,用于更灵活地定义类型。

typescript
interface Person {
  name: string;
  age: number;
  email: string;
}

// Partial<Person> 表示所有属性都是可选的
const partialPerson: Partial<Person> = { name: "John" };

// Required<Person> 表示所有属性都是必需的
const requiredPerson: Required<Person> = {
  name: "John",
  age: 30,
  email: "john@example.com"
};

// Readonly<Person> 表示所有属性都是只读的
const readonlyPerson: Readonly<Person> = {
  name: "John",
  age: 30,
  email: "john@example.com"
};

// readonlyPerson.name = "Jane"; // 错误:无法分配到 "name" ,因为它是只读属性

// Record<K, T> 表示键为 K 类型,值为 T 类型的对象
const record: Record<string, number> = {
  "a": 1,
  "b": 2,
  "c": 3
};

13. 装饰器

装饰器是一种特殊类型的声明,它可以附加到类声明、方法、访问器、属性或参数上,用于修改类的行为。

typescript
// 类装饰器
function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }
  greet() {
    return `Hello, ${this.greeting}`;
  }
}

// 方法装饰器
function enumerable(value: boolean) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.enumerable = value;
  };
}

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

  @enumerable(false)
  greet() {
    return `Hello, ${this.name}`;
  }
}

14. 与 JavaScript 的兼容性

TypeScript 完全兼容 JavaScript,你可以将现有的 JavaScript 代码直接转换为 TypeScript 代码,无需修改。

typescript
// 这是一个有效的 TypeScript 代码,与 JavaScript 完全相同
function add(a, b) {
  return a + b;
}

console.log(add(1, 2)); // 3

15. 工具类型

TypeScript 提供了许多内置的工具类型,用于操作和转换类型。

typescript
// Exclude<T, U> 从 T 中排除可以赋值给 U 的类型
type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"

// Extract<T, U> 从 T 中提取可以赋值给 U 的类型
type T1 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"

// NonNullable<T> 从 T 中排除 null 和 undefined
type T2 = NonNullable<string | number | null | undefined>; // string | number

// ReturnType<T> 获取函数返回值的类型
type T3 = ReturnType<() => string>; // string

// Parameters<T> 获取函数参数的类型
type T4 = Parameters<(a: number, b: string) => void>; // [number, string]

总结

TypeScript 提供了许多强大的特性,使代码更加可靠、可维护和易于理解。这些特性包括:

  • 静态类型检查
  • 类型推断
  • 接口
  • 泛型
  • 模块
  • 命名空间
  • 类型别名
  • 联合类型和交叉类型
  • 字面量类型
  • 枚举
  • 高级类型
  • 装饰器
  • 与 JavaScript 的兼容性
  • 工具类型

这些特性使 TypeScript 成为一种非常强大的编程语言,特别适合大型项目和团队协作。通过使用 TypeScript,你可以编写更安全、更可维护的代码,减少运行时错误,提高开发效率。