当前位置: 首页 > news >正文

TypeScript 从入门到精通:完整教程与实战应用(二)

8. 模块和命名空间

模块:

// math.ts
export function add(x: number, y: number): number {return x + y;
}// app.ts
import { add } from './math';
console.log(add(1, 2));

命名空间:

namespace Validation {export interface StringValidator {isAcceptable(s: string): boolean;}const lettersRegexp = /^[A-Za-z]+$/;export class LettersOnlyValidator implements StringValidator {isAcceptable(s: string) {return lettersRegexp.test(s);}}
}let validators: { [s: string]: Validation.StringValidator } = {};
validators["Letters only"] = new Validation.LettersOnlyValidator();

9. 装饰器 (Decorators)

装饰器是一种特殊类型的声明:

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

第三部分:TypeScript 实战 (70-100%)

10. 与前端框架集成

React + TypeScript:

import React, { useState } from 'react';interface Props {name: string;age?: number;
}const Greeting: React.FC<Props> = ({ name, age = 18 }) => {const [count, setCount] = useState<number>(0);return (<div><h1>Hello {name}, age {age}</h1><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}>Click me</button></div>);
};export default Greeting;

Vue + TypeScript:

<template><div><h1>Hello {{ name }}, age {{ age }}</h1><p>You clicked {{ count }} times</p><button @click="increment">Click me</button></div>
</template><script lang="ts">
import { defineComponent, ref } from 'vue';export default defineComponent({props: {name: {type: String,required: true},age: {type: Number,default: 18}},setup(props) {const count = ref(0);function increment() {count.value++;}return {count,increment};}
});
</script>

11. Node.js 后端开发

Express + TypeScript:

import express, { Request, Response } from 'express';interface User {id: number;name: string;
}const app = express();
app.use(express.json());const users: User[] = [{ id: 1, name: 'Alice' },{ id: 2, name: 'Bob' }
];app.get('/users', (req: Request, res: Response<User[]>) => {res.json(users);
});app.post('/users', (req: Request<{}, {}, User>, res: Response<User>) => {const newUser = req.body;users.push(newUser);res.status(201).json(newUser);
});const PORT = 3000;
app.listen(PORT, () => {console.log(`Server running on http://localhost:${PORT}`);
});

12. 测试与调试

Jest + TypeScript:

// math.test.ts
import { add, subtract } from './math';describe('math functions', () => {it('should add two numbers', () => {expect(add(1, 2)).toBe(3);});it('should subtract two numbers', () => {expect(subtract(5, 3)).toBe(2);});
});// math.ts
export function add(a: number, b: number): number {return a + b;
}export function subtract(a: number, b: number): number {return a - b;
}

13. 高级配置与优化

tsconfig.json 详解:

{"compilerOptions": {"target": "es6", // 编译目标版本"module": "commonjs", // 模块系统"strict": true, // 启用所有严格类型检查选项"esModuleInterop": true, // 兼容 CommonJS 和 ES Modules"skipLibCheck": true, // 跳过声明文件的类型检查"forceConsistentCasingInFileNames": true, // 强制文件名大小写一致"outDir": "./dist", // 输出目录"rootDir": "./src", // 源文件目录"baseUrl": ".", // 解析非相对模块的基础目录"paths": { // 路径映射"@/*": ["src/*"]},"declaration": true, // 生成 .d.ts 声明文件"sourceMap": true // 生成 source map},"include": ["src/**/*"],"exclude": ["node_modules", "**/*.spec.ts"]
}

14. 性能优化与最佳实践

  1. 使用 const 断言:

    const colors = ["red", "green", "blue"] as const;
  2. 避免 any 类型:

    // 不好
    function logValue(val: any) {console.log(val);
    }// 好
    function logValue<T>(val: T) {console.log(val);
    }
  3. 使用类型守卫:

    function isString(test: any): test is string {return typeof test === "string";
    }
  4. 合理使用 unknown 类型:

    function safeParse(json: string): unknown {return JSON.parse(json);
    }
  5. 使用实用类型:

    interface User {id: number;name: string;age: number;
    }type PartialUser = Partial<User>; // 所有属性可选
    type ReadonlyUser = Readonly<User>; // 所有属性只读
    type UserWithoutAge = Omit<User, 'age'>; // 排除 age 属性
     

http://www.xdnf.cn/news/6841.html

相关文章:

  • stl 容器 – map
  • 校平机:精密制造的“材料雕刻家“
  • MQTTClient.c中的协议解析与报文处理机制
  • SpringBoot运维问题
  • FreeRTOS任务通知
  • 51单片机实验五:A/D和D/A转换
  • 前端:uniapp框架中<scroll-view>r如何控制元素进行局部滚动
  • ASP.NET MVC 实现增删改查(CRUD)操作的完整示例
  • 从代码学习深度学习 - 小批量随机梯度下降 PyTorch 版
  • Spring Boot启动流程深度解析:从main()到应用就绪的完整旅程
  • Starrocks 数据均衡DiskAndTabletLoadReBalancer的实现
  • 使用Lean 4和C#进行数学定理证明与逻辑推理
  • RAG 实战|用 StarRocks + DeepSeek 构建智能问答与企业知识库
  • edge browser for linux debian
  • 23种设计模式-创建型模式之建造者模式(Java版本)
  • AWS上构建基于自然语言的数值和符号计算系统
  • 设计模式每日硬核训练 Day 15:享元模式(Flyweight Pattern)完整讲解与实战应用
  • MCP协议在纳米材料领域的深度应用:从跨尺度协同到智能研发范式重构
  • spring响应式编程系列:总体流程
  • Ubuntu18.04安装Qt5.12
  • 在PyCharm中部署AI模型的完整指南
  • 鸿蒙-跨设备互通,设备互通提供跨设备的相机、扫描、图库访问能力,平板或2in1设备可以调用手机的相机、扫描、图库等功能。
  • 【VSCode】在 VSCode 中运行 HTML 页面并通过 HTTPS 访问
  • 在pycharm中搭建yolo11分类检测系统--PyQt5学习(二)
  • 发现“横”字手写有难度,对比两个“横”字
  • CSS3笔记
  • 小知识合集 慢慢更新
  • vue,uniapp解决h5跨域问题
  • uniapp打包IOS私钥证书过期了,如何在非mac系统操作
  • PDK中technology file从tf格式转换为lef格式