前言
时隔一年。。第二篇ts学习笔记重出江湖(很惭愧…),继上一篇TypeScript学习笔记(01)–类型后,此篇介绍语法部分的剩下内容及一个小案例来实践ts用法;
正文
如何创建ts文件并使用
1.使用命令行创建ts环境
- npm i typescripe -g
- tsc -V 检测版本
- 新建learn.ts文件,index.html页面
- 命令行运行 tsc ./learn.ts在同层目录下生成 learn.js
- html页面引用js文件即可,不会自动更新
2. 让vscode创建ts文件并编译
- 运行tsc -init 创建tsconfig.json文件
- 设置 outDir 文件目录为./js/
- 使用vscode打开终端运行任务,tsc监视-即可在同层目录下生成js文件
语法
1.变量
- js : let 变量名 = 值
- ts : let 变量名:变量类型 = 值
2.常见类型
- js原有类型:
string number boolean Array Null undefined Symbol Object - ts新增类型:
- tuple(元祖):元组是一个包含固定数量的元素和相关类型的数组
- enum(枚举)
- any(任意类型):一般在取dom的时候使用
- never:底部类型,可以付给所有其他类型
- void:表示无含义,一般在没有返回值的函数中使用
3.类型推断
- 一般在同一行,没有给类型的,会进行类型推断;
let a = 18; ==>let a:number = 18 - 联合类型;不确定时,可以给多个类型:
let a :string|null = fun()
4.函数
-
返回值类型
function 函数名():返回值类型{ }
let 变量名:变量类型 = 函数名() -
形参类型
function 函数名(参数1:类型,参数2:类型):返回值类型{ }
let 变量名:变量类型 = 函数名(实参1,实参2) -
带默认值的参数传递
function 函数名(参数1:类型=默认值1,参数2:类型=默认值2):返回值类型{ }
1 2 3 4 5 6 7 8 9 10 11 12 | function add(x:number=2,y:number=3):number{ console.log(x+y) return x+y } add() //5 add(6) //9 add(6,5) //11 add(undefined,5) //7 // * 不传参 add()--> add(2,3) // * 传一个参数 add(6) --> add(6,3) // * 两个参数都传 add(6,5)-->add(6,5) // * 传后一个参数 add(undefined,5)-->add(2,5) |
-
形参不确定的情况
第一个参数确定,后面的参数用展开运算符,并且是数组类型指代;
1 2 3 4 5 6 7 8 9 10 | function edit(x?:number,...y?:number[]):void{ let num:number = x?x:1 for (const ele of y) { num += ele } console.log(num) } edit()//1 edit(3)//3 edit(1,2,3,4,5) //15 |
5.类
- 构造函数+new 方法创造类
- class函数创造类
根据 ES6的class 构造函数中的例子用ts方法改写类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Demo2 { x:string|number; y:string|number; constructor(x:string|number,y:string|number) { this.x = x this.y = y } test():string{ return `${this.x}是X的值,${this.y}是Y 的值` } static chanage():string { return '测试是否能被继承' } } let str2 = new Demo2(5, 6).test() let str3 = Demo2.chanage() console.log(str2)//5是X的值,6是Y 的值 console.log(str3)//测试是否能被继承 |
案例—— ts中类的使用
需求:1.加载评论列表,2.文章评论存入localstorage,3.页面删除评论;

index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./js/main.js"></script> </head> <body> <h3>内容</h3> <p>TypeScript学习笔记(02)--函数,类其他语法;</p> <p>作者:jcat_李小黑 ,文章链接 <a href="https://blog.csdn.net/weixin_43216105?t=1">jcat_李小黑的csdn</a></p> <h3>评论</h3> <ul id="textBox"></ul> <hr> <h3>发表评论</h3> <textarea name="textarea" id="textarea" cols="30" rows="10"></textarea> <button id="btnOK">发表评论</button> </body> </html> |
main.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | // 模拟后台请求初始化一个评论 const json: any = [ { id: 1, data: '文章很好!' }, { id: 2, data: '哈哈哈哈哈' }, ] // 使用class来完成该功能 class ContData { jsonKey: string;//TsDemo contId: string; //主键名称 constructor(jsonKey: string, contId: string) { this.jsonKey = jsonKey this.contId = contId }; //取值 readData(): any { let localJson: string | null = localStorage.getItem(this.jsonKey) if (localJson !== null) { return JSON.parse(localJson) } else { let jsonData: string = JSON.stringify(json) localStorage.setItem('TsDemo', jsonData) return json } } // 存值 saveData(arrData: object[]): void { let localJson: string | null = JSON.stringify(arrData) localStorage.setItem(this.jsonKey, localJson) } // 新增 addData(data: string): number { // 1.拿到本地数据 let arr: any = this.readData() // 2.创建一个新的评论对象并赋值 let newObj: any = { "data": data } // 3.自动生成主键id let newId = arr.length > 0 ? arr[arr.length - 1][this.contId] + 1 : 1 newObj[this.contId] = newId // 4.将对象增加到数组中 arr.push(newObj) // 5.保存新的数组 this.saveData(arr) // 6.返回新的id return newId } // 删除 deletData(id: number | string): boolean { // 读取本地数组 let arr: any = this.readData() // 找到对象 let index = arr.findIndex((e: any) => e[this.contId] == id) // 删除对象--如果大与-1就能找到 if (index > -1) { arr.splice(index, 1) this.saveData(arr) return true } return false } } //创建li function makeDom(id: string | number, data: string): any { let textBox: any = document.getElementById('textBox') let li = document.createElement('li') li.innerText = '评论' + id + ':' + data textBox.appendChild(li) let btn = document.createElement('button') btn.innerText = '删除评论' btn.setAttribute('data-id', id.toString()) btn.onclick = remove li.appendChild(btn) } // 删除 function remove(el: any) { let btn = el.srcElement let li = btn.parentNode li.parentNode.removeChild(li) let id = btn.getAttribute('data-id') cont.deletData(id) } // 页面操作 let cont = new ContData('TsDemo', 'id') window.onload = function () { // 进入页面后取值赋值评论给页面 let arr = cont.readData() for (const el of arr) { makeDom(el.id, el.data) } // 新增 let textarea: any = document.getElementById('textarea') let btnOK: any = document.getElementById('btnOK') btnOK.onclick = function (): any { let str = textarea.value let newId = cont.addData(str) makeDom(newId, str) textarea.value = "" } } |
结语
经过以上的学习,对ts在html中的用法也应该熟悉起来了,我认为的TypeScript其实就是给JavaScript加了一些规范,还是那句话:ts是js的超集,学好ts的根本还是熟练运用js!好了,在html中的用法已经学完了,下一篇讲:TypeScript+Vue+Vuex语法是如何使用的?
over~
如果本文对你有帮助的话,请不要忘记给我点赞打call哦~o( ̄▽ ̄)do