TypeScript(02)——函数,class类其他语法及ts在html页面中如何使用案例

TypeScript学习笔记(02)——函数,class类其他语法及ts在html页面中如何使用案例

  • 前言
  • 正文
    • 如何创建ts文件并使用
      • 1.使用命令行创建ts环境
      • 2. 让vscode创建ts文件并编译
    • 语法
    • 1.变量
    • 2.常见类型
    • 3. 修饰符(Modifiers)
    • 4.readonly 只读
    • 5.类型推断
    • 6.函数
    • 7.类
    • 案例—— ts中类的使用
  • 结语

前言

时隔一年。。第二篇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. 修饰符(Modifiers)

  • public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public 的;
  • private 修饰的属性或方法是私有的,不能在声明它的类的外部访问;
  • protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类中也是允许被访问的
 public readonly msg!: number | string;
 private readonly msg!: number | string;
 protected readonly msg!: number | string;

4.readonly 只读

只读属性关键字,只允许出现在属性声明或索引签名或构造函数中。

 readonly msg!: number | string;
 public readonly msg!: number | string;

5.类型推断

  • 一般在同一行,没有给类型的,会进行类型推断;
    let a = 18; ==>let a:number = 18
  • 联合类型;不确定时,可以给多个类型:let a :string|null = fun()

6.函数

  • 返回值类型
    function 函数名():返回值类型{ }
    let 变量名:变量类型 = 函数名()

  • 形参类型
    function 函数名(参数1:类型,参数2:类型):返回值类型{ }
    let 变量名:变量类型 = 函数名(实参1,实参2)

  • 带默认值的参数传递

    function 函数名(参数1:类型=默认值1,参数2:类型=默认值2):返回值类型{ }

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)
  • 形参不确定的情况

    第一个参数确定,后面的参数用展开运算符,并且是数组类型指代;

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

7.类

  • 构造函数+new 方法创造类
  • class函数创造类
    根据 ES6的class 构造函数中的例子用ts方法改写类
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.页面删除评论;
TypeScript(02)——函数,class类其他语法及ts在html页面中如何使用案例_第1张图片
index.html


<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <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_李小黑的csdna>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

// 模拟后台请求初始化一个评论
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学习笔记(03)——如何在vue项目中使用TypeScript?

附:TS学习笔记合集:

  • TypeScript学习笔记(01)——TS的类型
  • TypeScript学习笔记(02)——函数,class类其他语法及ts在html页面中如何使用案例
  • TypeScript学习笔记(03)——vue/cil项目中如何使用TypeScript语法合集
  • TypeScript学习笔记(04)——VueCil4全家桶 + TypeScript + LocalStorage 完成的本地便签案例

over~
如果本文对你有帮助的话,请不要忘记给我点赞打call哦~o( ̄▽ ̄)do

你可能感兴趣的:(TypeScript)