1. 首页 > IT综合教程 > 正文

it教程FG125-TypeScript基础

内容大纲

1. TypeScript简介

TypeScript是微软开发的一种静态类型检查的编程语言,是JavaScript的超集,它可以编译成纯JavaScript。TypeScript的主要特点包括:

  • 静态类型检查:在编译时检测类型错误,提高代码质量
  • 类型推断:自动推断变量类型,减少手动类型标注
  • 接口:定义对象的结构和类型
  • :支持面向对象编程
  • 泛型:提供类型参数化能力
  • 模块化:支持ES模块和CommonJS模块
  • 工具支持:丰富的IDE支持和开发工具

TypeScript广泛应用于大型前端项目,特别是使用React、Vue等框架的项目,它可以帮助开发者减少运行时错误,提高代码可维护性。更多学习教程www.fgedu.net.cn

2. TypeScript安装

2.1 全局安装TypeScript

$

# 全局安装TypeScript

$

npm install -g typescript

$

# 检查TypeScript版本

$

tsc –version

$

Version 5.0.4

2.2 项目本地安装TypeScript

$

# 初始化项目

$

npm init -y

$

# 本地安装TypeScript

$

npm install –save-dev typescript

$

# 创建tsconfig.json配置文件

$

npx tsc –init

2.3 编译TypeScript文件

$

# 编译单个TypeScript文件

$

tsc hello.ts

$

# 编译整个项目

$

tsc

3. TypeScript基本类型

3.1 原始类型

// 字符串
let name: string = "John";

// 数字
let age: number = 30;

// 布尔值
let isAdmin: boolean = true;

// 空值
let empty: void = undefined;

// null和undefined
let n: null = null;
let u: undefined = undefined;

// 任意类型
let anyValue: any = "Hello";
anyValue = 123;
anyValue = true;

// 未知类型
let unknownValue: unknown = "Hello";
// 需要类型断言才能使用
let length: number = (unknownValue as string).length;

3.2 数组类型

// 数字数组
let numbers: number[] = [1, 2, 3, 4, 5];

// 字符串数组
let strings: string[] = ["a", "b", "c"];

// 泛型数组
let values: Array = [1, 2, 3];

3.3 元组类型

// 元组类型
let person: [string, number] = ["John", 30];

// 访问元组元素
console.log(person[0]); // "John"
console.log(person[1]); // 30

3.4 联合类型

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

// 类型保护
function printValue(value: string | number) {
    if (typeof value === "string") {
        console.log(`String: ${value}`);
    } else {
        console.log(`Number: ${value}`);
    }
}

3.5 字面量类型

// 字符串字面量类型
let direction: "north" | "south" | "east" | "west" = "north";

// 数字字面量类型
let dice: 1 | 2 | 3 | 4 | 5 | 6 = 3;

// 布尔字面量类型
let booleanLiteral: true | false = true;

4. TypeScript接口

4.1 基本接口

// 定义接口
interface Person {
    name: string;
    age: number;
    email?: string; // 可选属性
    readonly id: number; // 只读属性
}

// 使用接口
let person: Person = {
    name: "John",
    age: 30,
    id: 1
};

// 错误:无法修改只读属性
// person.id = 2;

4.2 函数接口

// 函数接口
interface AddFunction {
    (a: number, b: number): number;
}

// 使用函数接口
let add: AddFunction = (a, b) => a + b;
console.log(add(1, 2)); // 3

4.3 索引签名

// 索引签名
interface StringMap {
    [key: string]: string;
}

// 使用索引签名
let map: StringMap = {
    name: "John",
    age: "30" // 注意:值也必须是字符串
};

// 数字索引签名
interface NumberArray {
    [index: number]: number;
}

let array: NumberArray = [1, 2, 3];

4.4 接口继承

// 基础接口
interface Person {
    name: string;
    age: number;
}

// 继承接口
interface Employee extends Person {
    employeeId: number;
    department: string;
}

// 使用继承后的接口
let employee: Employee = {
    name: "John",
    age: 30,
    employeeId: 123,
    department: "IT"
};

5. TypeScript类

5.1 基本类

// 定义类
class Person {
    // 属性
    name: string;
    age: number;
    
    // 构造函数
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    
    // 方法
    greet() {
        return `Hello, my name is ${this.name}`;
    }
}

// 创建实例
let person = new Person("John", 30);
console.log(person.greet()); // "Hello, my name is John"

5.2 访问修饰符

// 访问修饰符
class Person {
    public name: string; // 公共属性
    private age: number; // 私有属性
    protected email: string; // 保护属性
    
    constructor(name: string, age: number, email: string) {
        this.name = name;
        this.age = age;
        this.email = email;
    }
    
    public getAge() {
        return this.age;
    }
}

// 子类
class Employee extends Person {
    constructor(name: string, age: number, email: string) {
        super(name, age, email);
    }
    
    getEmail() {
        return this.email; // 可以访问保护属性
    }
}

let person = new Person("John", 30, "john@fgedu.net.cn");
console.log(person.name); // 可以访问公共属性
// console.log(person.age); // 错误:无法访问私有属性
let employee = new Employee("Jane", 25, "jane@fgedu.net.cn");
console.log(employee.getEmail()); // 可以通过方法访问保护属性

5.3 只读属性

// 只读属性
class Person {
    readonly id: number;
    name: string;
    
    constructor(id: number, name: string) {
        this.id = id;
        this.name = name;
    }
}

let person = new Person(1, "John");
console.log(person.id); // 1
// person.id = 2; // 错误:无法修改只读属性

5.4 静态属性和方法

// 静态属性和方法
class MathUtil {
    static PI: number = 3.14159;
    
    static add(a: number, b: number): number {
        return a + b;
    }
}

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

5.5 抽象类

// 抽象类
abstract class Animal {
    abstract makeSound(): void;
    
    move(): void {
        console.log("Moving...");
    }
}

// 子类必须实现抽象方法
class Dog extends Animal {
    makeSound(): void {
        console.log("Woof!");
    }
}

let dog = new Dog();
dog.makeSound(); // "Woof!"
dog.move(); // "Moving..."

6. TypeScript泛型

6.1 泛型函数

// 泛型函数
function identity(value: T): T {
    return value;
}

// 使用泛型函数
let number = identity(1);
let string = identity("Hello");

// 类型推断
let boolean = identity(true);

6.2 泛型接口

// 泛型接口
interface Box {
    value: T;
}

// 使用泛型接口
let numberBox: Box = { value: 123 };
let stringBox: Box = { value: "Hello" };

6.3 泛型类

// 泛型类
class Stack {
    private items: T[] = [];
    
    push(item: T): void {
        this.items.push(item);
    }
    
    pop(): T | undefined {
        return this.items.pop();
    }
}

// 使用泛型类
let numberStack = new Stack();
numberStack.push(1);
numberStack.push(2);
console.log(numberStack.pop()); // 2

let stringStack = new Stack();
stringStack.push("a");
stringStack.push("b");
console.log(stringStack.pop()); // "b"

6.4 泛型约束

// 泛型约束
interface Lengthwise {
    length: number;
}

function logLength(value: T): void {
    console.log(value.length);
}

// 可以传递字符串
logLength("Hello"); // 5

// 可以传递数组
logLength([1, 2, 3]); // 3

// 错误:数字没有length属性
// logLength(123);

7. TypeScript模块

7.1 ES模块

// module.ts
export const PI = 3.14159;

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

export interface Person {
    name: string;
    age: number;
}

// app.ts
import { PI, add, Person } from './module';

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

const person: Person = {
    name: "John",
    age: 30
};

7.2 命名空间

// namespace.ts
namespace Math {
    export const PI = 3.14159;
    
    export function add(a: number, b: number): number {
        return a + b;
    }
}

// 使用命名空间
console.log(Math.PI); // 3.14159
console.log(Math.add(1, 2)); // 3

8. TypeScript最佳实践

生产环境建议

  • 使用严格模式(strict: true)
  • 合理使用类型推断,减少不必要的类型标注
  • 使用接口定义对象结构
  • 使用泛型提高代码复用性
  • 使用命名空间或模块组织代码
  • 使用访问修饰符封装内部实现
  • 使用抽象类和接口实现多态
  • 使用TypeScript ESLint插件保持代码质量
  • 编写类型声明文件(.d.ts)
  • 使用tsconfig.json配置编译选项
  • 合理使用类型断言,避免过度使用any类型
  • 使用工具类型(如Partial、Pick、Omit等)

风哥风哥提示:TypeScript是一种强大的类型系统,建议在大型项目中使用,它可以帮助开发者减少错误,提高代码可维护性。

学习交流加群风哥微信: itpux-com

学习交流加群风哥QQ113257174

更多学习教程公众号风哥教程itpux_com

author:www.itpux.com

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息