TypeScript 快速入门 + 应用
一、ts 入门
(1)概述
TypeScript(简称 TS)是一种由微软开发的开源编程语言,它是 JavaScript(JS)的一个超集,添加了可选的静态类型和基于类的面向对象编程。
TypeScript 的主要目的是帮助开发大规模应用程序,它通过引入强类型系统和编译时错误检查,使得代码更加健壮和易于维护。
(2)特点
-
静态类型检查:TypeScript 允许你在代码中指定变量的类型。如果类型不匹配,TypeScript 编译器会在编译时报错,这有助于在代码运行之前捕捉到潜在的错误。
-
类和接口:TypeScript 支持使用类和接口来构建程序。这使得 TypeScript 特别适合使用面向对象方法进行复杂应用程序的开发。
-
模块化:TypeScript 支持模块,使得开发者可以将代码分解成可重用的模块。
-
ES6 功能及以上:TypeScript 支持 ECMAScript 6 标准的所有新特性,并且随着标准的发展持续更新。这包括箭头函数、解构赋值等。
-
工具链支持:TypeScript 与多种工具链兼容良好,例如常见的前端构建工具(如 Webpack、Rollup 等)和编辑器(如 Visual Studio Code、Sublime Text 等)。这些工具通常提供对 TypeScript 的内置支持或者可以通过插件支持。
-
渐进式:TypeScript 允许你逐渐地将现有的 JavaScript 项目迁移到 TypeScript,你可以在项目中同时使用 TypeScript 和 JavaScript。
(3)工作流程:
- 编写 TypeScript 代码:在文件中使用
.ts
或.tsx
(对于使用 JSX 语法的文件)扩展名。 - 编译 TypeScript 代码:使用 TypeScript 编译器(通常是命令行工具
tsc
)将 TypeScript 代码编译为 JavaScript 代码。这一步会进行类型检查并且转换为相应版本的 JavaScript。 - 运行 JavaScript 代码:编译生成的 JavaScript 代码可以在任何支持 JavaScript 的环境中运行,例如浏览器或 Node.js。
(4)数据类型
具体代码运行console看之后的运行单个文件
1.number + string + boolean + null + undefined + symbol + bigint
let num: number = 12121const str: string = 'blackstone'const bool: boolean = falseconst nu: null = nullconst un: undefined = undefinedconsole.log('null ?= undefined', nu === un) //null ?= undefined false//symbol
const sy1: symbol = Symbol()
const sy2: symbol = Symbol()
console.log('sy1 === sy2?', sy1 === sy2)//bigint
const bg1: bigint = 324325431213345654n
const bg2: bigint = BigInt(324325431213345654)
2. array + function + object
//array
const arr1: string[] = ['a', 'b', 'c']
const arr2: Array<number> = [1, 2, 3]//function
const fun1: (params: string) => boolean = params => falsetype Fun = (params: string) => boolean
const fun2: Fun = () => false
const fun3: Fun = () => truefunction fun4(params: string): boolean {return false
}//object
const obj: object = {a: 1,b: 2
}
console.log('obj', obj) //obj { a: 1, b: 2 }interface Obj {a: stringb: string
}
const obj1: Obj = {a: '1',b: '2'
}
console.log('obj1', obj1) //obj1 { a: '1', b: '2' }const obj2: { a: string; b: string } = {a: 'a',b: 'n'
}
console.log('obj2', obj2) //obj2 { a: 'a', b: 'n' }
3. void + any + never
// void
const v = (): void => {}// any
let x;
x = 1;
x = 'sss';//never 永远不会有返回值
const n1 = (): never => {throw new Error();
}const n2 = (): never =>{while(true){}
}
4. enum
// 枚举类型// 0. 数字枚举
enum OrderStatus {Pending,Shipped,Completed,Canceled,Unkown
}
console.log('OrderStatus.Pending', OrderStatus.Pending) // OrderStatus.Pending 0
console.log('OrderStatus.Completed', OrderStatus.Completed) // OrderStatus.Completed 2// 1.常量枚举
// 使用的时候才做 运算
const enum ConstOrderStatus {Pending,Shipped,Completed,Canceled,Unkown
}
console.log('ConstOrderStatus.Canceled', ConstOrderStatus.Canceled)
// ConstOrderStatus.Canceled 3// 2. 字符串枚举
enum OrderStatus2 {Pending = 'Pending',Shipped = 'Shipped',Completed = 'Completed',Canceled = 'Canceled',Unkown = 'Unkown'
}
console.log('OrderStatus2.Pending', OrderStatus2.Pending) // OrderStatus2.Pending Pending
console.log('OrderStatus2.Completed', OrderStatus2.Completed) // OrderStatus2.Completed Completed// 3. 异构枚举
enum OrderStatus3 {Pending,Shipped,Completed = 'Completed',Canceled = 'Canceled',Unkown = 'Unkown'
}
console.log('OrderStatus3.Shipped', OrderStatus3.Shipped) //OrderStatus3.Shipped 1
console.log('OrderStatus3.Unkown', OrderStatus3.Unkown) //OrderStatus3.Unkown Unkown
-
-
// let b = 2; // b = '3'; //Type 'string' is not assignable to type 'number'.let a: any = 1; (a as string) = '2';
-
(5)接口 interface + 类型别名 type
- interface
- 描述对象的结构和属性
- 可以被实现(implements)或扩展(extends)
- type
- 表示(对象、联合类型、交叉类型)类型的别名,允许为任何类型创建别名
- 进行复杂 的类型操作
//接口 与 类型别名
interface User {name: stringage: numbereat(): void
}type UserType = {name: stringage: number
}type UserType1 = Userfunction funa(params: User): User {return params
}function funb(params: UserType): UserType {return params
}
// 接口 扩展 接口
interface Person extends User {email: string
}const q: Person = {name: '杨理',age: 24,email: 'isyangli@126.com',eat() {console.log('大吃特吃')}
}
q.name = 'YL'
console.log('person', q)
// person {
// name: 'YL',
// age: 24,
// email: 'isyangli@126.com',
// eat: [Function: eat]
// }
q.eat() //大吃特吃//类实现接口
class Man implements User {name: stringage: numberemail: stringconstructor(name: string, age: number, email: string) {this.name = namethis.age = agethis.email = email}eat() {}
}interface Chick {age: number
}interface Dog {run()
}
// type类型别名
type Animal1 = Chick | Dog
type Animal2 = Chick & Dogconst aa: Animal1 = {age: 14
}// 所有的属性和方法 都要声明
const bb: Animal2 = {age: 15,run() {}
}
(6)类型保护
- 使用typeof 做类型判断
- 只有number、string、boolean、symbol四种类型 可以被保护
- instanceof 做对象类型判断
// 1.判断一个值的长度
const lengthFunction = (a: string | number) => {if (typeof a === 'string') {return a.length;}if (typeof a === 'number') {return a.toString().length;}return 0;
}
// 2.判断一个实体 属于哪种对象
class Person1 {name1: stringage1: numberconstructor(name1: string, age1: number) {this.name1 = name1this.age1 = age1}
}class Person2 {name2: stringage2: numberconstructor(name2: string, age2: number) {this.age2 = age2this.name2 = name2}
}const lengthFunctionInstanceOf = (a: Person1 | Person2) => {if (a instanceof Person1) {return a.name1}if (a instanceof Person2) {return a.name2}return 0
}
(7)类型断言
const lengthFun = (a: string | number) => {// a.length //Property 'length' does not exist on type 'number'.return (a as string).length
}
(8)索引类型
- 对象索引的类型
- 对象的属性(key)叫做属性
// 索引类型
interface Obj {[key: string]: string
}interface Products {[id: number]: Products
}const product = {name: 'nick',price: 200
}const products = {1: {name: 'nick',price: 200},2: {name: 'adidas',price: 300}
}
(9)映射类型
- 根据已有的类型 创建新的类型
- 使用 操作符 来创建新的类型
const product = {name: 'nick',price: 200
}interface Product {name: stringprice: number
}// 常见操作符
type Keys = keyof Product //'name' | 'price'
type Tp = typeof product
(10)泛型
- 本质
- 类型的复用
- 类型的简单差异使用泛型参数代替
- 算法的复用
- 程序不用过多数据类型,更多的关注算法的结构
- 类型的复用
- 4种
- 泛型函数
- 泛型接口
- 泛型类
- 泛型别名
// 泛型
interface Res {code: numbermessage: string
}interface Res1 {code: numbermessage: stringdata: string
}interface Res2 {code: numbermessage: stringkey: string
}// function transData(res) {
function transData<T extends Res>(res: T) {if (res.code === 200) {return res.message}throw new Error('系统错误')
}transData<Res1>({code: 200,message: '',data: ''
})transData<Res2>({code: 200,message: '',key: '这是 一个 key'
})// (1) 泛型函数
type Fn1<T> = (a: T) => boolean
type Fn2<T> = (a: string) => T
type Fn3<T, R> = (a: T) => Rconst fn1: Fn1<string> = a => {console.log(a)return false
}const fn2: Fn1<number> = a => {console.log(a)return false
}// (2) 泛型接口
interface Product<T = string> {name: stringprice: numberother: T
}const p: Product<string> = {name: '1',price: 100,other: '3'
}const productu: Product<number> = {name: '',price: 200,other: 333
}const producti: Product = {name: '',price: 200,other: '333'
}// 泛型类
class ProductClass<T> {name: stringprice: numberother: Tconstructor(name: string, price: number, other: T) {;(this.name = name), (this.price = price), (this.other = other)}
}interface Phone {version: stringsize: number
}interface Snacks {productionDate: stringexpirationDate: string
}new ProductClass<Phone>('三星手机', 8900, {version: 's24 u',size: 5000
})new ProductClass<Snacks>('干脆面', 0.5, {productionDate: '2024-4-25',expirationDate: '2024-11-18'
})// 类型别名
type MutableArray<T> = T[]const numbers: MutableArray<number> = [1, 2, 3, 4]
const strings: MutableArray<string> = ['a', 'b', 'c']
(11)类型编程的四个范式
- 访问性修饰工具类型 Partial Readonly
- 结构性工具类型 Pick Omit Record
- 集合工具类型 NonNullable Exclude
- 模式匹配工具类型 ReturnType
二、ts 应用
(1)基础环境构建
1. 创建 npm 环境
PS C:\Desktop\软件开发\前端\typeScript> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.See `npm help init` for definitive documentation on these fields
and exactly what they do.Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
2. 创建 ts 环境
PS C:\Desktop\软件开发\前端\typeScript> npm i typescript -gchanged 1 package in 34s
PS C:\Desktop\软件开发\前端\typeScript> tsc -v
Version 5.4.5
PS C:\Desktop\软件开发\前端\typeScript> tsc -initCreated a new tsconfig.json with:
在package.json中,添加build命令
"scripts": {"build": "tsc",
执行命令生成js文件
3. 创建前端开发环境
PS C:\Desktop\软件开发\前端> npm create vite@latest
Need to install the following packages:
create-vite@5.2.3
Ok to proceed? (y) y> npx
> create-vite√ Project name: ... ts-learning-web
√ Select a framework: » React
√ Select a variant: » TypeScriptScaffolding project in C:\Desktop\软件开发\前端\ts-learning-web...Done. Now run:cd ts-learning-webnpm installnpm run dev
启动
PS C:\Desktop\软件开发\前端> cd .\ts-learning-web\
PS C:\Desktop\软件开发\前端\ts-learning-web> npm install
npm warn deprecated inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm warn deprecated glob@7.2.3: Glob versions prior to v9 are no longer supported
npm warn deprecated rimraf@3.0.2: Rimraf versions prior to v4 are no longer supportedadded 213 packages, and audited 214 packages in 2m41 packages are looking for fundingrun `npm fund` for detailsfound 0 vulnerabilities
PS C:\Desktop\软件开发\前端\ts-learning-web> npm run dev> ts-learning-web@0.0.0 dev
> viteVITE v5.2.13 ready in 631 ms➜ Local: http://localhost:5173/➜ Network: use --host to expose➜ press h + enter to show help
(2)运行指定ts文件
具体配置