ts的接口和泛型的基本语法

  • ts的接口和泛型的基本语法已关闭评论
  • 136 次浏览
  • A+
所属分类:Web前端
摘要

一、接口  1.接口定义       接口是一种规范的定义,它定义行为和规范,在程序设计中接口起到限制和规范的作用。

一、接口

 

1.接口定义

       接口是一种规范的定义,它定义行为和规范,在程序设计中接口起到限制和规范的作用。

2.接口的声明与使用

//声明对象类型接口  interface Person {    name: string,    age: number,    say(): void  }    // 使用接口  let person: Person = {    name: 'jack',    age: 18,    say() {    }  }

 // 示例:用对象型接口封装原生ajax请求
 
  interface Config{
    type:string; //get post
    url:string;
    data?:string;//可选传入
    dataType:string;//json xml等
}

//原生js封装的ajax
function ajax(config:Config){

    var xhr=new XMLHttpRequest();
    xhr.open(config.type,config.url,true);

    if(config.data){
        xhr.send(config.data);
    }else{
        xhr.send();
    }

    xhr.onreadystatechange=function(){

        if(xhr.readyState==4 && xhr.status==200){
            console.log('请求成功');
            if(config.dataType=='json'){
                console.log(JSON.parse(xhr.responseText));
            }else{
                console.log(xhr.responseText)
            }
        }
    }
}
ajax({
    type:'get',
    data:'name=zhangsan',
    url:'http://www.example.com/api', // api接口url
    dataType:'json'
})

 

3.函数类型接口

 // 对方法传入的参数以及返回值进行约束 批量约束   interface encypt{     (key:string, value:string):string;   }      var md5:encypt = function (key, value):string{     return key + ' ' + value    }   console.log(md5('李', '二狗'))      var sha1:encypt = function(key, value):string{     return key + '--' + value   }   console.log(sha1('dog', 'zi'))

 

 

 

4.接口(interface)和类型别名(type)的对比

// 相同点:都可以给对象指定类型  //定义接口  interface Person {    name: string,    age: number,    say(): void  }  //类型别名  type Person= {    name: string,    age: number,    say(): void  }    // 使用接口  let person: Person = {    name: 'jack',    age: 18,    say() {    }  }  // 不同点:1.接口只能为对象指定类型,接口可以通过同名来添加属性            // 2.类型别名不仅可以指定类型,还可以为任意类型指定别名   interface Bat {     name: string    }    interface Bat {    age: number    }    function fgh(id: Bat) {        }    fgh({    name: "dfsd",    age: 12    })

   // 声明已有类型(即取别名)
   type A = number;
   // 字面量类型
    type B = 'foo';
   // 元组类型
   type C = [number, string];
   // 联合类型
   type D = number | boolean|string;

 

5.接口可选属性和只读性

interface FullName{         readonly id:string         firstName:string;         lastName?:string; }   function getName(name:FullName){         console.log(name) }   getName({         firstName:'zhang', })

6.任意类型

interface UserInfo {    name: string,    age: number,    sex?: string    [propName: string]: any //一旦定义了任意属性,那么确定属性和可选属性类型都必须是任意属性类型的子类    }  const myInfo: UserInfo = {    name: "jack",    age: 18,    test: "123123",    test1: 23  }

7.接口的继承

// 使用extends关键字继承,实现接口的复用  interface Point2D {   x: number;   y: number }  interface Point3D extends Point2D {   z: number }  let P: Point3D = {    x: 1,    y: 2,    z: 3  }

8.通过implements来让类实现接口

interface Single {    name: string,    sing(): void  }  class Person implements Single {    name = "tom"    sing(): void {      console.log("qwe");     }  }  //Person 类实现接口Single,意味着Person类中必须提供Single接口中所用的方法和属性

二、泛型

1.泛型的理解

泛型是指在预先定义函数、接口或者类的时候,不预先指定数据的类型,而是在使用的时候指定,从而实现复用。

2.使用泛型变量来创建函数

// 使用泛型来创建一个函数
//格式: 函数名<泛型1,泛型2> (参数中可以使用泛型类型):返回值也可以是泛型类型
function id<T>(value: T): T {    return value  }
// 其中 T 代表 Type,在定义泛型时通常用作第一个类型变量名称。
// 但实际上 T 可以用任何有效名称代替。除了 T 之外,以下是常见泛型变量代表的意思:

// K(Key):表示对象中的键类型;
// V(Value):表示对象中的值类型;
// E(Element):表示元素类型。
 

 //调用泛型函数  const num = id(10)  const str = id("as")  const ret = id(true)  //多个泛型变量  function identity <T, U>(value: T, message: U) : T {  console.log(message); return value;  }  console.log(identity(68, "Semlinker"));    

3.泛型约束

// 如果我们直接对一个泛型参数取 length 属性, 会报错, 因为这个泛型根本就不知道它有这个属性  // 没有泛型约束  function fn<T>(value: T): T {    console.log(value.length);//error    return value  }  //通过extends关键字添加泛型约束,传入的参数必须有length属性  interface Ilength {    length: number  }  function fn1<T extends Ilength>(value: T): T {    console.log(value.length);    return value  }  fn1("asdad")  fn1([1,4,5])  fn1(12323) //报错

4.泛型接口

// 接口可以配合泛型来使用,以增加其灵活性,增强复用性  // 定义  interface IdFunc<T> {    id: (value: T) => T    ids: () => T[]  }  // 使用  let obj: IdFunc<number> = { //使用时必须要加上具体的类型    id(value) {      return value    },    ids() {      return [1, 4, 6]    }  }  //函数中的使用
  interface ConfigFn<T>{
    (value:T):T
  }
  function getData<T>(value:T):T{
    return value
  }
  var myGetData:ConfigFn<string>=getData
  myGetData('abc')

 

5.泛型类

//创建泛型类 class GenericNumber<Numtype>{   defaultValue: Numtype   constructor(value: Numtype) {     this.defaultValue = value   }  } // 使用泛型类 const myNum = new GenericNumber<number>(100)

6.泛型工具类型

   作用:TS内置了一些常用的工具类型,用来简化TS中的一些常见操作

 6.1 partail

// partial<T>的作用就是将某个类型中的属性全部变为可选项? interface Props {   id: string,   children: number[] } type PartailProp = Partial<Props>  let obj1: PartailProp = {  }

6.2 Readonly

// Readonly<T>的作用将某个类型中的属性全部变为只读 interface Props {   id: string,   children: number[] } type PartailProp = Readonly<Props>  let obj1: PartailProp = {   id: "213123",   children: [] } obj1.id="122" //报错

6.3 pick

// Pick<T, K>的作用是将某个类型中的子属性挑出来,变成包含这个类型部分属性的子类型 interface Todo {   title: string,   desc: string,   time: string } type TodoPreview = Pick<Todo, 'title' | 'time'>; const todo: TodoPreview = {   title: '吃饭',   time: '明天' }

6.4 Record

// Record<K , T>的作用是将K中所有的属性转换为T类型 interface PageInfo {   title: string } type Page = 'home'|'about'|'other'; const x: Record<Page, PageInfo> = {   home: { title: "xxx" },   about: { title: "aaa" },   other: { title: "ccc" }, };

6.5. Exclude

// Exclude<T,U>的作用是将某个类型中属于另一个类型的属性移除掉 type Prop = "a" | "b" | "c" type T0 = Exclude<Prop, "a">; // "b" | "c" const t: T0 = 'b';