Skip to content

TypeScript 开发指南

简介

TypeScript 是 JavaScript 的超集,它添加了静态类型系统,使代码更加健壮和可维护。本文将介绍 TypeScript 的核心概念、类型系统和最佳实践。

基础类型

1. 基本类型

typescript
// 基本类型定义
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];
enum Color { Red, Green, Blue }
let c: Color = Color.Green;
let notSure: any = 4;
let u: undefined = undefined;
let n: null = null;

2. 类型断言

typescript
// 类型断言示例
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;

// 另一种断言语法
let strLength2: number = (<string>someValue).length;

接口

1. 接口定义

typescript
// 基本接口
interface User {
  name: string;
  age: number;
  email?: string;  // 可选属性
  readonly id: number;  // 只读属性
}

// 实现接口
class UserImpl implements User {
  readonly id: number;
  name: string;
  age: number;
  
  constructor(id: number, name: string, age: number) {
    this.id = id;
    this.name = name;
    this.age = age;
  }
}

2. 函数类型

typescript
// 函数接口
interface SearchFunc {
  (source: string, subString: string): boolean;
}

// 实现函数接口
let mySearch: SearchFunc = function(source: string, subString: string) {
  return source.search(subString) !== -1;
};

高级类型

1. 联合类型

typescript
// 联合类型
type StringOrNumber = string | number;

function processValue(value: StringOrNumber) {
  if (typeof value === "string") {
    return value.toUpperCase();
  } else {
    return value.toFixed(2);
  }
}

2. 类型守卫

typescript
// 类型守卫
interface Bird {
  fly(): void;
  layEggs(): void;
}

interface Fish {
  swim(): void;
  layEggs(): void;
}

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    pet.swim();
  } else {
    pet.fly();
  }
}

泛型

1. 泛型函数

typescript
// 泛型函数
function identity<T>(arg: T): T {
  return arg;
}

// 使用泛型函数
let output = identity<string>("myString");
let output2 = identity("myString");  // 类型推断

2. 泛型接口

typescript
// 泛型接口
interface GenericIdentityFn<T> {
  (arg: T): T;
}

// 实现泛型接口
let myIdentity: GenericIdentityFn<number> = function(x: number): number {
  return x;
};

装饰器

1. 类装饰器

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;
  }
}

2. 方法装饰器

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

class Example {
  @enumerable(false)
  method() {}
}

模块

1. 导出

typescript
// 导出声明
export interface StringValidator {
  isValid(s: string): boolean;
}

export class ZipCodeValidator implements StringValidator {
  isValid(s: string) {
    return s.length === 5 && /^\d+$/.test(s);
  }
}

2. 导入

typescript
// 导入声明
import { ZipCodeValidator } from "./ZipCodeValidator";
import * as validator from "./ZipCodeValidator";

let myValidator = new ZipCodeValidator();
let myValidator2 = new validator.ZipCodeValidator();

最佳实践

1. 类型定义

typescript
// 类型定义文件
// types.d.ts
declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}

declare module "*.json" {
  const value: any;
  export default value;
}

2. 配置管理

json
// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "declaration": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

工具链

1. 开发工具

json
{
  "devDependencies": {
    "typescript": "^4.5.0",
    "@types/node": "^16.0.0",
    "ts-node": "^10.0.0",
    "ts-loader": "^9.0.0"
  }
}

2. 代码质量工具

json
{
  "devDependencies": {
    "eslint": "^8.0.0",
    "@typescript-eslint/parser": "^5.0.0",
    "@typescript-eslint/eslint-plugin": "^5.0.0",
    "prettier": "^2.0.0"
  }
}

总结

TypeScript 通过静态类型系统提供了更好的开发体验和代码质量保证。通过合理使用类型系统、接口、泛型等特性,可以构建出更加健壮和可维护的应用程序。

参考资源