Typescript 基础
概述
TypeScript 是 JavaScript 的超集,提供了静态类型检查,编译为纯 JavaScript。
核心优势:
- 类型检查 — 编译期间发现错误,避免运行时问题
- 更好的维护性 — 修改接口字段时,所有引用处都会报错提示
- IDE 支持 — 智能提示、自动补全、重构
Typescript vs Javascript
| TypeScript | JavaScript |
|---|---|
| JavaScript 的超集 | 脚本语言,创建动态网页 |
| 编译期间发现并纠正错误 | 运行时才能发现错误 |
| 强类型,支持静态和动态类型 | 弱类型,没有静态类型选项 |
| 最终编译为 JavaScript | 直接在浏览器中使用 |
| 支持模块、泛型和接口 | 不支持泛型或接口 |
开发环境搭建
全局安装
bash
npm i typescript -g
tsc xxx.ts # 编译 ts 文件为 js
tsc --init # 生成 tsconfig.jsonnpm i typescript -g
tsc xxx.ts # 编译 ts 文件为 js
tsc --init # 生成 tsconfig.jsonWebpack 打包
bash
npm install webpack webpack-cli webpack-dev-server -D
npm install ts-loader cross-env html-webpack-plugin clean-webpack-plugin -Dnpm install webpack webpack-cli webpack-dev-server -D
npm install ts-loader cross-env html-webpack-plugin clean-webpack-plugin -Djs
// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
entry: './src/index.ts',
output: {
filename: 'main.js',
path: 'dist',
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_module/,
},
],
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
},
devServer: {
contentBase: './dist',
compress: false,
host: 'localhost',
port: 8089,
},
devtool: process.env. NODE_ENV === 'production' ? false : 'inline-source-map',
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/template/index.html',
}),
],
}// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
entry: './src/index.ts',
output: {
filename: 'main.js',
path: 'dist',
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_module/,
},
],
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
},
devServer: {
contentBase: './dist',
compress: false,
host: 'localhost',
port: 8089,
},
devtool: process.env. NODE_ENV === 'production' ? false : 'inline-source-map',
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './src/template/index.html',
}),
],
}json
// package.json
{
"scripts": {
"start": "cross-env NODE_ENV=development webpack-dev-server --config ./webpack.config.js",
"build": "cross-env NODE_ENV=production webpack --config ./webpack.config.js"
}
}// package.json
{
"scripts": {
"start": "cross-env NODE_ENV=development webpack-dev-server --config ./webpack.config.js",
"build": "cross-env NODE_ENV=production webpack --config ./webpack.config.js"
}
}tsconfig 配置
通过 tsc --init 生成 tsconfig.json,核心字段:
| 字段 | 说明 |
|---|---|
compilerOptions | 编译选项 |
include | 需要编译的文件 |
exclude | 排除的文件 |
compilerOptions 常用选项
json
{
"compilerOptions": {
"target": "es5", // 编译目标版本
"module": "commonjs", // 模块规范
"lib": ["dom"], // 引入的库文件
"outDir": "./dist", // 输出目录
"rootDir": "./src", // 源码目录
"strict": true, // 启用所有严格检查
"noImplicitAny": true, // 禁止隐式 any
"strictNullChecks": true, // 严格 null 检查
"moduleResolution": "node", // 模块解析策略
"baseUrl": ".", // 模块解析基目录
"paths": { "*": ["node_modules/*"] }, // 路径映射
"allowSyntheticDefaultImports": true, // 允许默认导入
"esModuleInterop": true, // ES 模块互操作
"experimentalDecorators": true, // 启用装饰器
"jsx": "preserve", // JSX 处理方式
"declaration": true, // 生成 .d.ts 文件
"sourceMap": true, // 生成 sourcemap
"downlevelIteration": true, // 迭代器兼容
"noEmit": false // 是否禁止输出
},
"include": ["./src/**/*.ts", "./src/**/*.d.ts"],
"exclude": ["node_modules"]
}{
"compilerOptions": {
"target": "es5", // 编译目标版本
"module": "commonjs", // 模块规范
"lib": ["dom"], // 引入的库文件
"outDir": "./dist", // 输出目录
"rootDir": "./src", // 源码目录
"strict": true, // 启用所有严格检查
"noImplicitAny": true, // 禁止隐式 any
"strictNullChecks": true, // 严格 null 检查
"moduleResolution": "node", // 模块解析策略
"baseUrl": ".", // 模块解析基目录
"paths": { "*": ["node_modules/*"] }, // 路径映射
"allowSyntheticDefaultImports": true, // 允许默认导入
"esModuleInterop": true, // ES 模块互操作
"experimentalDecorators": true, // 启用装饰器
"jsx": "preserve", // JSX 处理方式
"declaration": true, // 生成 .d.ts 文件
"sourceMap": true, // 生成 sourcemap
"downlevelIteration": true, // 迭代器兼容
"noEmit": false // 是否禁止输出
},
"include": ["./src/**/*.ts", "./src/**/*.d.ts"],
"exclude": ["node_modules"]
}TS 大纲
主要学习路线:基础类型 → 接口与函数 → 泛型与类 → 枚举 → 高级类型 → 声明文件 → 装饰器 → 工程实践。
Cao Note