四----ts了解

四----ts了解一 为什么要用 ts 1 ts 是 js 的加强版 它给 js 增加了可选的静态类型和面向对象编程 它的功能比 js 只多不少 2 ts 是面向对象的语言 它包含类和接口的概念 3 ts 在开发时就能给出编译错误 而 js 需要运行时才能发现 4

大家好,我是讯享网,很高兴认识大家。

一、为什么要用ts?

1)ts是js的加强版,它给js增加了可选的静态类型和面向对象编程,它的功能比js只多不少。 2)ts是面向对象的语言,它包含类和接口的概念; 3)ts在开发时就能给出编译错误,而js需要运行时才能发现; 4)ts作为强类型语言,明确数据类型,代码可读性比较强; 5)ts中有很多很方便的特性比如可选链。 

讯享网

二、typescript分类

讯享网let A :number = 1; 

2、枚举 enum

enum Status { 
    START = 'start',//若没有赋值,则默认1,2,3...这样 STOP = 'stop', } const a = Status.START; 

3、type/interface 定义特定对象结构等

讯享网type UserInfo= { 
    name:string; grade:number; } interface UserInfo { 
    name:string; grade?:number;//问号表示可填可不填 } 

4、联合类型|(一次一种类型)

interface UserInfoA { 
    name:string; year:number; } interface UserInfoB { 
    height:number; } function test(param: UserInfoA|UserInfoB)//参数必须事其中之一 

5、交叉类型&(两个或多个的合并类型)

讯享网interface UserInfoA { 
    name:string; year:number; } interface UserInfoB { 
    height:number; } function test(param: UserInfoA&UserInfoB)//参数必须事这两个类型的并集 

5、typeof 用来获取一个变量声明或对象类型

typeof 'a' = 'string';//true function toArray(x: number):Array<number> { 
   return [x]} type y = typeof toArray;//y为(x:number)=>number[] 

6、keyof操作符可以用来获取对象中的所有key值

讯享网interface UserInfoA { 
    name:string; year:number; } type a = keyof UserInfoA;//只能是‘name’和‘year’ const b :a = 'name'; const c:a = 'year';//只能赋值这两个不然会报错 

7、in 用来遍历枚举类型

type keys = 'a'|'b'|'c'; type b = { 
    [key in keys] :any; }//b最后为{a:any;b:any;c:any} 

8、extends 继承,通常用来做泛型约束,即定义的泛型继承一个类型

讯享网interface User { 
    name:string; } function test<T extends User>(params:T):T{ 
    return params; } test(1);//会报错 test({ 
   name:'sss',value:1})//正确 

9、Partial Partial把某个类型里的属性全部变成可选项?

interface User { 
    name:string; } type B = Paritial<User>//以后b的属性name可填可不填 

10、Required Required就是将某个类型里的所有属性变成必填项
11、Readonly Readonly将所有属性变成可读,不可写,即不可以被重新赋值修改
12、Record<K,T>将K中所有属性的值转化为T类型,并返回新的对象类型

讯享网interface PageInfo{ 
    title:string; } type page = 'a'|'b'|'c'; type mix = Record<page,PageInfo>; const a :mix = { 
    'a':{ 
   title:'xxx'}, 'b':{ 
   title:'xxx'}, 'c':{ 
   title:'xxx'} } 

13、Exclude<T,U> 将其中类型T中属于另一个U类型的属性去掉,假设u属于T,则剩下T中没有u的部分。

type a = Exclude<'a'|'b'|'c','a'>//只剩下‘b’|'c' type b = Exclude<'a'|'b'|'c','a'|'b'>//只剩下‘c’ 

14、Extract<T,U>将T,U中的交集提取出来

讯享网type a = Extract<'a'|'b'|'c','b'|'c'>//'b'|'c' type b = Extract<string|number|(()=>void),Function>//交集是函数,因为()=>void是函数的一种,所以结果是()=>void 

三、简单的装饰器(通过装饰器的写法去修改原有逻辑,不修改原有的代码)

1、计算函数执行时间


讯享网

export function measure(target:any,name:any,descriptor:any){ 
    const val = descriptor.value; descriptor.value = async function(){ 
    const starttime = Date.now(); //this指向不改变,普通函数this指向调用它的对象实例 const value = await val.apply(this,arguments); console.log('执行时间为'+Date.now()-starttime); return value; } return descriptor; } //使用 @measure // 写在要计算的那个方法前面 

2、缓存

讯享网let map = new Map(); export function autoCache(target:any,name:any,descriptor:propertyDescriptor){ 
    const val = descriptor.value; descriptor.value = async function(...args:any){ 
    const key = name+JSON.stringfy(args); let value; if(!map.get(key)){ 
    //这里用一个promise包裹返回的值,在cache里能在返回失败的时候清空原来的值,这里的promise.resolve只是为了包一层,如果传入的值是promise实例则直接使用,如果不是则包一层正常执行resolve的promise实例返回,这样就都能使用.then链式调用来执行正确和错误方法了 //这种方式刷新就没了,它是存在内存中的 value = await Promise.resolve(val.apply(this,args)).catch((_)=>map.set(key,null)); } map.set(key,value) return map.get(key); } return descriptor; } //使用 @autoCache // 写在要重新请求的那个方法前面 

四、通过几个小实例来了解ts写法

1、封装路由跳转约束跳转参数

import { 
    Dictionary } from "vue-router/types/router"; import Router from "../router"; export type BaseRouteType = Dictionary<string>; export enum routerPath { 
    index = '/index', home = '/', } export interface indexParam extends BaseRouteType { 
    userName:string, } export interface homeParam extends BaseRouteType { 
    name:string, } export interface routerParams { 
    [routerPath.index]:indexParam; [routerPath.home]:homeParam; } export class routerHelper { 
    public static replace<T extends routerPath>(path: T,params: routerParams[T]) { 
    Router.replace({ 
    path:path, params:params, }) } public static push<T extends routerPath>(path:routerPath, params: routerParams[T]) { 
    Router.push({ 
    path:path, params:params, }) } } //这时要跳转对应的路径一定需要包含对应的参数,不然在开发编译时就会报错 /比如 routerHelper.push(routerPath.index,{ 
   userName:''}) 

2、倒计时

讯享网export enum countDownStatus { 
    runing, paused, stoped, } export enum countDownEventName { 
    START='start', STOP='stop', RUNNING='running', } export interface remianTimeData { 
    days:number, hours:number, minutes:number, seconds:number, count:number, } export interface countDownMap { 
    [countDownEventName.RUNNING]: [remianTimeData,number], [countDownEventName.START]: []; [countDownEventName.STOP]: []; } export class countDown extends EventEmitter<countDownMap>{ 
    private static COUNT:number = 100; private static SECONDS:number = 10*countDown.COUNT; private static MINUTES:number = 60*countDown.SECONDS; private static HOURS:number = 60*countDown.MINUTES; private static DAYS:number = 24*countDown.HOURS; private endTime: number; private step: number; private status:countDownStatus = countDownStatus.stoped; private remianTime: number = 0; constructor(time:number, step: number) { 
    super(); this.endTime = time; this.step = step; this.startCount(); } public startCount() { 
    this.emit(countDownEventName.START); this.status = countDownStatus.runing this.countTime(); } public countTime(){ 
    if(this.status !== countDownStatus.runing){ 
    return; } this.remianTime = Math.max(this.endTime - Date.now(), 0); this.emit(countDownEventName.RUNNING, this.fomateTime(this.remianTime),this.remianTime); if(this.remianTime>0) { 
    setTimeout(() => { 
    this.countTime(); }, this.step) } else { 
    this.stop(); } } public fomateTime(remianTime: number){ 
    let time = remianTime; const days = time/countDown.DAYS; time = time%countDown.DAYS; const hours = time /countDown.HOURS; time = time%countDown.HOURS; const minutes = time/countDown.MINUTES; time = time%countDown.MINUTES; const seconds = time/countDown.SECONDS time = time%countDown.SECONDS; const count = time/countDown.COUNT; return { 
   days,hours,minutes,seconds,count} } public stop(){ 
    this.emit(countDownEventName.STOP); this.status = countDownStatus.stoped; } } 

五、interface跟type的区别

//对象 interface a{ 
    name:string, grade:number } type a = { 
    name:string, grade:number, } //函数 interface b { 
    (name:string,grade:number):void } type b = (name:string,grade:number)=>void 

2)都允许扩展extends,且两者之间可以互相扩展

讯享网//interface extend interface a { 
    name:string } interface b extends a{ 
    age:number } //type extends type a = { 
   name:string} type b = a & { 
   age:number} //interface extends type type a = { 
   name:string} interface b extend a{ 
    age:number } //type extends interface interface a { 
   name:string} type b = a&{ 
   age:number} 
//基本类型 type a = string; //联合类型 interface a = { 
   name:string} interface b = { 
   age:number} type c = a | b; //具体定义每个数组的位置类型的叫元组 type c = [a,b] //获取一个变量类型的时候用typeof const div = document.getElementByid('id') type a = typeof div 

六:如何基于一个已有类型,扩展出大部分内容相似,但有部分区别的的类型?

1、首先可以通过Pick和Omit

讯享网interface test { 
    name:string, sex:string, height:number } //pick将Sex里的sex属性类型与test里的sex属性类型一致,如果要修改只需要修改test里的即可 type Sex = Pick<test,'sex'> const a :Sex = { 
   sex:'女'} //去掉sex属性 type WithoutSex = Omit<test,'sex'>; const b :WithoutSex = { 
   name:'11',height:11} 

还有partial和required 泛型
泛型是指定义接口,类的时候不具体指定类型,而是等到使用时才指定的一种特性
例如:

interface a <T = any> { 
   name:T} type b = a<string> type c = a<number> const bb:b = { 
   name:'aa'} const cc:c = { 
   name:12} 

七、一个问号(?)两个问号(??)一个感叹号(!)两个感叹号(!!)的用法和区别

1、一个问号(?)表示 可选属性或者可选参数,即实例化的对象或者传参可设置也可不设置。

讯享网 interface Person { 
    name: string; age?: number; } function greet(name: string, age?: number) { 
    console.log(`Hello, ${ 
     name}! You are ${ 
     age} years old.`); } 

2、两个问号(??)表示一个空值合并运算符,用于检查一个值是否为null或undefined,并在其为null或undefined时提供一个默认值

const value1 = null; const value2 = 42; const result1 = value1 ?? "Default Value"; // Output: Default Value const result2 = value2 ?? "Default Value"; // Output: 42 
讯享网// ! 就是将之后的结果取反,比如: // 当 isNumber(input) 为 True 时返回 False; isNumber(input) 为 False 时返回True const a = !isNumber(input); 

属性成员:

// 因为接口B里面name被定义为可空的值,但是实际情况是不为空的,那么我们就可以 // 通过在class里面使用!,重新强调了name这个不为空值 class A implemented B { 
    name!: string } 

强制链式调用:

讯享网 // 我们确信这个字段100%出现,那么就可以添加!,强调这个字段一定存在 new Error().stack!.split('\n'); function greet(person: Person) { 
    console.log(`Hello, ${ 
     person.name.toUpperCase()}!`); } const person: Person = { 
    name: "John" }; greet(person!); 

4、两个感叹号(!!)
let is_valid = !!test; 在TypeScript中,这种用法是将变量test转换为布尔类型,并将结果赋值给变量is_valid。!!是逻辑非运算符的两次连续使用,它会将变量转换为布尔类型的值。如果test的值为真,则is_valid将被赋值为true;如果test的值为假,则is_valid将被赋值为false。这种用法可以用于简单地判断一个变量是否有值或是否为真。

const emptyStr = '' const nonEmptyStr = 'test' const emptyStrBool = !!emptyStr //false const nonEmptyStrBool = !!nonEmptyStr //true 
小讯
上一篇 2025-03-16 20:38
下一篇 2025-03-29 22:19

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/89646.html