TS

作者: 羊驼驼驼驼 | 来源:发表于2022-08-05 10:24 被阅读0次
ts.jpeg
  • 定义

📖 融合了面向对象后端的思想的超级版的javaScript语言

  • 环境搭建
  1. 🍬 npm方式
npm init -y
yarn add typescript -D
tsc --init
  1. 🍬 brew
 brew reinstall typescript
 tsc --init
  • 优势
  1. 🍬 编译时静态类型检测:函数或方法传参或变量赋值不匹配时,会出现编译错误提示,避开了开发期间的大量低级错误;
  2. 🍬 自动提示:变量类型、变量属性,不用来回切换文件或者不小心写错导致的编码隐患;
  3. 🍬 引入了泛型:让前端底层源码具备了高可扩展性的优势,同时也有类型安全检查的优势
  4. 🍬 强大的d.ts声明文件:声明文件像一本书的目录一样,清晰直观的展示了依赖文件库的接口,type类型,类,函数,变量等声明;
  5. 🍬 轻松 编译成JS文件:即使TS文件有错误,绝大情况也能编译出JS文件
  6. 🍬 灵活性高:尽管TS是一门强类型语言,但是也提供了any和as any 类型,提升了TS的灵活度
  • tsconfig.json
{
  { "rootDir": "./src",   // 指定 TS 文件源码目录
  "outDir": "./dist",  // 指定 TS 文件编译成JS的输出目录
  "target": "es2016", // 指定  TS 编译成 JS 后的js版本
  "module": "commonjs", // TS 编译成 JS 后采用的模块规范 commonjs amd cmd es5
  "lib": ["DOM", "ES2020"], // 指定TS编码期间可以使用的库文件版本,例:ES5不支持Set集合
  "strict": true, // 启用严格检查模式【开启当前模式相当于开启下列几项】
  "noImplicitAny": true, // 一般是指表达式或函数参数上有隐含的any类型时报错
  "experimentalDecorators": true, // 启用 ES7 装饰器实验开启选项
  "emitDecoratorMetadata": true, // 启用装饰器元数据开启选项
  "declaration": true, // 指定 TS 文件编译后生成的对应的.d .ts 文件
  "removeComments": true, //  TS 文件编译后删除所有的注释
  "strictNullChecks": true, // null 和 undefined即是值,也是类型,null 和 undefined 值只能赋值给 any ,unknown和它们各自的类型
  "baseUrl": "src" // 工作根目录,解析非相对模块的基地址
  "paths": {
    "@/datatype/*": ["datatype/*"]
  },  
  // 有一些依赖库 为了兼容CommonJS规范、AMD规范这两种的规范中相互兼容
  // 使用了 export = ,将两者规范统一
  // 设置为true表示允许依赖库里出现export = 这种兼容规范导出的格式
  // TS 可以import from 导入
  "esModuleInterop": true,    
},
"include": [ // 需要编译的ts文件一个*表示文件匹配**表示忽略文件深度的问题
     "./src/**/*.ts" // 匹配src下所有的ts文件
 ],
 "exclude": [
    "./src/**/test"
 ]
}
  • 类型注解、类型推断
  1. 🍬 类型注解
let price:number = 0

type StudentType = { name: string, age: number }
let stuObj:StudentType = { name: 'wangwu', age: 3}
  1. 🍬 类型推导
let count = 3
let custObj = { name: 'wangwu', 'age': 3}
  • any、unknown
  1. 🍬 any
    可以作为任何数据类型的父类也可以作任何数据类型的子类
    any 不能作类型推导,但是可以强行写属性
let price:any = "abc"
let total:number = price
  1. 🍬unknown
    可以作为任何数据类型的父类,但是不能作任何数据类型的子类
    不能作类型推导,也不能强制写属性
let stuName:unknown = 'wangwu'
let stuAge:number = stuName
  • 函数、函数类型、rest参数
  1. 🍬 函数
function info(name: string, age: number) {
    console.log("name:", name, "age:" ,age)
    return 55
}
info("wangwu", 33)
  1. 🍬 函数类型
type TypeInfoFun = (name: string, age: number) => number
let info: TypeInfoFun =
    function(name, age) {
        console.log("name:", name, "age:" ,age)
        return 55
    }
info("wangwu", 33)
  1. 🍬 rest 参数
function info(name: string, age: number, ...rest: any) {
    console.log("name:", name, "age:", age, "rest:", rest )
    return 55
}
info("wangwu", 33, "hello", 12345)
  1. 🍬 函数类型升级及函数解构
// 函数类型升级
type TypeStuobj = { username: string, age: number, phone: string }
function info(stuobj: TypeStuobj) {
    console.log("name:", stuobj.username, "age:", stuobj.age)
    return 3
}
let stuObj:TypeStuobj={ username: "wangwu", age: 12, phone: '17600821234' }
info(stuObj)

// 函数解构
function  subInfo({username, age}: TypeStuobj) {
    console.log("name:", username, "phone:", age)
    return 3
}
subInfo({username: 'lala', age: 22, phone: '123'})
  • 运行ts文件,首先安装ts-node:npm install ts-node,WebStorm安装ts-node插件Run Configuration for TypeScript,重启IDE
运行结果.png
  1. 🍬 BigInt
  • tsconfig.json需要设置"lib": ["DOM", "ES2020"]
const max = BigInt(Number.MAX_SAFE_INTEGER)
console.log(max)
const maxBigOne = max + BigInt(1)
console.log(maxBigOne)
const maxBigTwo = max + BigInt(2)
console.log(maxBigTwo)

console.log(maxBigOne === maxBigTwo)
运行结果.png
简写
  • tsconfig.json需要设置"target": "es2020"
const max = BigInt(Number.MAX_SAFE_INTEGER)
console.log(max)
const maxBigOne = max + 1n
console.log(maxBigOne)
const maxBigTwo = max + 2n
console.log(maxBigTwo)

console.log(maxBigOne === maxBigTwo)
  1. 🍬 Never
  • dataFlowAnalysisWithNever 涵盖了DataFlow的所有可能类型
  • 使用never避免出现未来扩展新的类没有对应类型的实现,目的是写出类型绝对安全的代码
type DataFlow = string | number

function dataFlowAnalysisWithNever(dataFlow: DataFlow) {
    if (typeof dataFlow === "string") {
        console.log("字符串类型:", dataFlow.length)
    } else if (typeof dataFlow === "number") {
        console.log("数值类型:", dataFlow.toFixed(2))
    } else {
        let data = dataFlow
    }
}

dataFlowAnalysisWithNever("人生海海 山山而川 不过尔尔")
dataFlowAnalysisWithNever(123)

  1. 🍬 枚举
    枚举的好处:1. 有默认值和可以自增值,节省编码时间;2.语义更清晰,可读性更强
  • 数字枚举
    双向映射,由key取值,由值取key
enum Week {
    Monday = 1,
    Tuesday,
    Wensday,
    Thirsday,
    Friday,
    Sarturday,
    Sunday
}
console.log(Week.Monday)
console.log(Week["Monday"])
console.log(Week[1])
console.log(Week[5])
运行结果.png

编译后(底层呈现)

var Week;
(function (Week) {
    Week[Week["Monday"] = 1] = "Monday";
    Week[Week["Tuesday"] = 2] = "Tuesday";
    Week[Week["Wensday"] = 3] = "Wensday";
    Week[Week["Thirsday"] = 4] = "Thirsday";
    Week[Week["Friday"] = 5] = "Friday";
    Week[Week["Sarturday"] = 6] = "Sarturday";
    Week[Week["Sunday"] = 7] = "Sunday";
})(Week || (Week = {}));
console.log(Week.Monday);
console.log(Week["Monday"]);
console.log(Week[1]);
console.log(Week[5]);
  • 字符串枚举
    由key取值
enum Weekend {
    Monday = "Monday",
    Tuesday = "Tuesday",
    Wensday = "Wensday",
    Thirsday = "Thirsday",
    Friday = "Friday",
    Sarturday = "Sarturday",
    Sunday = "Sunday"
}

console.log(Weekend.Monday)
console.log(Weekend["Monday"])
运行结果.png

编译后(底层呈现)

var Weekend;
(function (Weekend) {
    Weekend["Monday"] = "Monday";
    Weekend["Tuesday"] = "Tuesday";
    Weekend["Wensday"] = "Wensday";
    Weekend["Thirsday"] = "Thirsday";
    Weekend["Friday"] = "Friday";
    Weekend["Sarturday"] = "Sarturday";
    Weekend["Sunday"] = "Sunday";
})(Weekend || (Weekend = {}));
console.log(Weekend.Monday);
console.log(Weekend["Monday"]);
  1. 🍬 元组
    1. 定义时的元素类型确定,但每个元素的类型可以不一样; 2.为元素赋值时,该值必须是当前位置的类型
let salary: [string, number, number, string] = ["王五", 8000, 6000, "hello"]
console.log(salary[0])
运行结果.png
  1. 🍬接口
    是为一系列同类对象或同类别的类提供属性定义和方法声明但没有任何赋值和实现的数据类型
interface Product {
    id: number;
    name: string;
    price: number;
    count: number;
}
function calToal(product: Product) {
    console.log("product总价:", product.price * product.count)
}
calToal({id: 1, name: "包", price: 100, count: 10})
运行结果.png
  • 可选属性
interface Product {
    id: number;
    name: string;
    price: number;
    count: number;
    mark?: string;
}
function calToal(product: Product) {
    console.log("product总价:", product.price * product.count)
}
calToal({id: 1, name: "包", price: 100, count: 10})
  • 可索引类型
interface Product {
    id: number;
    name: string;
    price: number;
    count: number;
    [key: string]: any;
}
function calToal(product: Product) {
    console.log("product总价:", product.price * product.count)
}
calToal({id: 1, name: "包", price: 100, count: 10, mark: '123'})
没毛病系列.png

相关文章

网友评论

      本文标题:TS

      本文链接:https://www.haomeiwen.com/subject/tvbovrtx.html