发布于 2025-04-27 12:00,更新于 2026-08-24 21:07,标签:TypeScript、全栈、前端、技术
TypeScript简略教程
TypeScript 简介、环境搭建、基础语法、类型系统、泛型、模块、高级特性到工程实践与优化建议的简明教程。

Loading…
发布于 2025-04-27 12:00,更新于 2026-08-24 21:07,标签:TypeScript、全栈、前端、技术
TypeScript 简介、环境搭建、基础语法、类型系统、泛型、模块、高级特性到工程实践与优化建议的简明教程。

本文主要内容转载自 CSDN 博主「前端极客探险家」,部分内容为本人原创(主要为原文补充了部分内容),遵循 CC 4.0 BY-SA 版权协议。原文链接:https://blog.csdn.net/idree/article/details/147563077
或许各位在书写JavaScript时遇到过许多难绷的语言设计缺陷,比如...

由于JavaScript是于1995年,网景的一个老哥(Brendan Eich)仅用10天开发的脚本语言(最初发明这个语言的动机仅仅是网景希望能在网页上添加一些动态效果),导致该语言在发明之初就具有诸多不完善之处。
所以在2012年,微软开发并开源了TypeScrpt作为JavaScript的超集(类似C++与C之间的关系),提供了静态类型检查等现代语言常见的规范。所有TS代码在运行前都会被编译为JS代码,这也使得开发者所写的TS代码可以在所有支持JS的环境中。
由于web浏览器可使用HTML解释JavaScript,JS在web开发领域一直有着很高的市占率。而TS能够完美兼容曾经的JS项目且在易用性等方面表现突出,使TS很快获得了大量开发者的喜爱。
简而言之,TypeScript具有以下优点:
npm install -g typescript创建 hello.ts:
const message: string = "Hello, TypeScript!";
console.log(message);编译为 JavaScript:
tsc hello.ts
node hello.js生成配置文件:
tsc --init常见配置说明:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true
}
}let isDone: boolean = false;
let age: number = 25;
let username: string = "Alice";
let list: number[] = [1, 2, 3];
let tuple: [string, number] =
enum Color { Red, Green, Blue }
let c: Color = Color.Green;接口是描述一个类“应该长什么”样的数据类型,其支持多继承,且不能创建实例。对于TS,接口相关代码在编译后会完全消失,不会带入编译产物的JS代码中。
TS的接口性质上和Java、C#、Go、Rust等语言的接口有诸多相似,可类比。
interface Person {
name: string;
age: number;
}
function greet(person: Person) {
console.log(`Hello, ${person.name}`);
}class Animal {
constructor(public name: string) {}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m.`);
}
}接口与类(TypeScript中)的主要区别:
| 性质 | 接口-interface | 类-class |
|---|---|---|
| 本质 | 类的“蓝图”,只描述类的形态 | 实体,既有数据 又有行为 |
| 编译后的状态 | 完全消失 | 会形成JS代码产物 |
| 是否可以创建实例 | 不可实例化 | 可以 new |
| 能有方法实现吗 | 只可声明方法,但不能有逻辑代码 | 可以有完整实现 |
| 能有构造函数吗 | 不可 | 可 |
| 是否可以多继承 | 可以,例如extends A, B, C | 不可,只能单继承 |
| 运行时是否还存在 | 不存在 | 存在 |
function add(x: number, y: number): number {
return x + y;
}
// 可选参数
function buildName(firstName: string, lastName?: string): string {
return lastName ? `${firstName} ${lastName}`
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;// 联合类型
function padLeft(value: string, padding: string | number) {
// ...
}
// 交叉类型
type Admin = {
name: string;
privileges: string[];
};
type Employee = {
name: string;
type Direction = "Up" | "Down" | "Left" | "Right";为了解决静态类型语言在类型安全以及代码复用上的问题,现代语言普遍应用泛型。
TypeScript中的泛型和Java中的泛型最像,与C++中的模板、C#中的泛型均很类似。
泛型就像是一个万能模具,装类型的数据的时候就是什么数据类型;泛型的加入为不同项目、不同场景中的代码模块复用提供了便利,加强了程序的健壮性。
function identity<T>(arg: T): T {
return arg;
}interface GenericIdentityFn<T> {
(arg: T): T;
}
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}// 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;
}
}装饰器类似Python中的函数装饰器、Java中的注解、C#中的特性、Rust中的属性宏,其类似将函数作为一个“基底”,通过“@其他函数名”的方式向这个函数上增加功能。
CSDN原文中给出的例子如下:
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
}但是这有一个更具体形象的例子:
// 定义一个装饰器:给方法加日志
function Log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`调用了 ${propertyKey},参数:`, args);
const result = original.apply(this, args);
console.log(`${propertyKey} 返回:`, result);
return result;
};
}
class Calculator {
@Log
add(a: number, b: number) {
return a + b;
}
}
const calc = new Calculator();
calc.add(1, 2);
// 输出:
// 调用了 add,参数: [1, 2]
// add 返回: 3interface Box {
height: number;
width: number;
}
interface Box {
scale: number;
}
// 合并后 Box 同时具有 height、width、scaletype IsString<T> = T extends string ? true : false;| 错误信息 | 原因 | 解决方法 |
|---|---|---|
| Property 'xxx' does not exist on type 'yyy' | 类型不匹配 | 检查类型定义或使用类型断言 |
| Cannot find name 'xxx' | 未引入模块或变量 | 导入正确模块或声明 |
| Argument of type 'xxx' is not assignable to parameter of type 'yyy' | 参数类型不匹配 | 修改参数或函数定义 |
npm create vite@latest my-ts-app -- --template vanilla-ts
cd my-ts-app
npm install
npm run devnpx create-react-app my-react-app --template typescript依赖安装:
npm install express
npm install -D typescript ts-node @types/node @types/express基本服务器代码:
import express from "express";
const app = express();
app.get("/", (req, res) => {
res.send("Hello from TS Server");
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});npm install -D eslint prettier eslint-config-prettier eslint-plugin-prettier.eslintrc.js:
module.exports = {
parser: "@typescript-eslint/parser",
extends: ["plugin:@typescript-eslint/recommended", "prettier"],
};tsconfig.json:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@components/*": ["components/*"]
}
}
}使用时:
import Button from "@components/Button";infer、extends、条件类型、映射类型TypeScript 是现代前端工程化的必备技术。掌握 TS,不仅可以提升项目质量,还可以在大型协作开发中立于不败之地。从入门到进阶,坚持动手实践,相信你可以成为 TypeScript 高手!
原文作者:前端极客探险家
原文链接:https://blog.csdn.net/idree/article/details/147563077
许可协议:CC 4.0 BY-SA